56. Merge Intervals

题目分析

基本思路先排序后扫描(线性扫描)

代码

时间复杂度 O(n*log(n))

/**
 * 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) {
        if(intervals == null || intervals.size() == 0) return intervals;
        List res = new ArrayList();
        // lambda 表达式的方式代替匿名内部类,按照 Interval 实例的 start 属性升序排序
        Collections.sort(intervals, (a, b) -> (a.start - b.start));
        int start = intervals.get(0).start;
        int end = intervals.get(0).end;
        for(Interval interval : intervals){
            // 此时两个相邻的空间需要合并
            /*
            [1, 3] [1, 2]
            [1, 2] [1, 3]
            [1, 4] [2, 2]
            ...
            */
            if(interval.start <= end) {
                end = Math.max(interval.end, end);
            } else {
               // 新开一个区间
                res.add(new Interval(start, end));
                start = interval.start;
                end = interval.end;
            }
        }
        // 追加最后一个区间
        res.add(new Interval(start, end));
        return res;
    }
}

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