Merge Overlapping Intervals

前端 未结 5 625
深忆病人
深忆病人 2021-02-04 10:48

Question : Given a set of time intervals in any order, merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals. Let th

5条回答
  •  情书的邮戳
    2021-02-04 11:25

    class Solution {
        public List merge(List intervals) {
            if (intervals.size() <= 1) {
                return intervals;
            }
            intervals.sort((i1, i2) -> Integer.compare(i1.start, i2.start));
            List result = new LinkedList();
            int start = intervals.get(0).start;
            int end = intervals.get(0).end;
            for(Interval interval : intervals) {
                if (interval.start <= end) {
                    end = Math.max(end, interval.end);
                }
                else {
                    result.add(new Interval(start, end));
                    start = interval.start;
                    end = interval.end;
                }
            }
            result.add(new Interval(start, end));
            return result;
        }
    }
    

提交回复
热议问题