Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

Show Company Tags
Show Tags
Show Similar Problems
/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        List<Interval> result = new ArrayList<>();
        if (intervals == null || intervals.size() == 0) return result;
        // Collections.sort, not Object.sort!!
        Collections.sort(intervals, new IntervalComparator());
        Interval pre = intervals.get(0);
        for (int i = 1; i < intervals.size(); i++) {
            Interval cur = intervals.get(i);
            if (cur.start <= pre.end) {
                Interval merged = new Interval(pre.start, cur.end);
                pre = merged;
            } else {
                // List.add(), no append
                result.add(pre);
                pre = cur;
            }
        }
        // Brefore return, should add pre again;
        result.add(pre);
        return result;
    }
    
    class IntervalComparator implements Comparator<Interval> {
        public int compare(Interval inter1, Interval inter2) {
            return inter1.start - inter2.start;
        }
    }
}
Advertisements