淘先锋技术网

首页 1 2 3 4 5 6 7

[LintCode] 156 合并区间

给出若干闭合区间,合并所有重叠的部分。

样例
样例1:
输入: [(1,3)]
输出: [(1,3)]
样例 2:
输入: [(1,3),(2,6),(8,10),(15,18)]
输出: [(1,6),(8,10),(15,18)]

挑战
O(n log n) 的时间和 O(1) 的额外空间。

/**
 * Definition of Interval:
 * public class Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this.start = start;
 *         this.end = end;
 *     }
 * }
 */

public class Solution {
    /**
     * @param intervals: interval list.
     * @return: A new interval list.
     */
    public List<Interval> merge(List<Interval> intervals) {
        List<Interval> list = new ArrayList<>();
        if (intervals.size() == 0) return list;
        
        Collections.sort(intervals, new Comparator<Interval>() {
            @Override
            public int compare(Interval o1, Interval o2) {
                return o1.start - o2.start;
            }
        });
        
        int s = intervals.get(0).start, e = intervals.get(0).end;
        for (int i = 0; i < intervals.size(); i++) {
            if (intervals.get(i).start <= e){
                e = Math.max(e, intervals.get(i).end);
            }else{
                list.add(new Interval(s, e));
                s = intervals.get(i).start;
                e = intervals.get(i).end;
            }
        }
        list.add(new Interval(s,e));
        return list;
    }
}