56 Merge Intervals

1. Question

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].

2. Implementation

(1) Scan Line

/**
 * 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; }
 * }
 */
class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        List<Interval> res = new ArrayList<>();

        if (intervals == null || intervals.size() == 0) {
            return res;
        }

        Collections.sort(intervals, new Comparator<Interval>() {
            @Override
            public int compare(Interval i1, Interval i2) {
                return i1.start - i2.start;
            }
        });
        Interval preInterval = null;

        for (Interval curInterval : intervals) {
            if (preInterval == null || preInterval.end < curInterval.start) {
                res.add(curInterval);
                preInterval = curInterval;
            }
            else if (preInterval.end < curInterval.end) {
                preInterval.end = curInterval.end;
            }
        }
        return res;
    }
}

3. Time & Space Complexity

Scan Line: 时间复杂度O(nlogn), 空间复杂度O(n)

Last updated