56. Merge Intervals

Description

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

Solution

Sort, time O(nlogn), space O(1)

首先将intervals按照start排序,然后从头开始遍历,逐个merge。

并不需要分治merge,那样会更复杂。从头开始逐个merge就可以了。如果遇到没有覆盖的interval,这个interval和后续所有的interval都不会产生覆盖了,直接将他加到结果集中就可以了。

/**
 * 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 merge(List intervals) {
        List res = new LinkedList<>();
        if (intervals == null || intervals.isEmpty()) {
            return res;
        }
        
        Collections.sort(intervals, new Comparator() {
            public int compare(Interval a, Interval b) {
                return a.start - b.start;
            }
        });
        
        Interval pre = intervals.get(0);

        for (int i = 1; i < intervals.size(); ++i) {
            Interval curr = intervals.get(i);
            if (curr.start > pre.end) {     // no overlap
                res.add(pre);
                pre = curr;
            } else {    // overlap
                pre.start = Math.min(pre.start, curr.start);
                pre.end = Math.max(pre.end, curr.end);
            }
        }
        
        res.add(pre);   // don't forget
        return res;
    }
}

你可能感兴趣的:(56. Merge Intervals)