[leetcode] 56. 合并区间

56. 合并区间

先对输入排序,然后从前到后判断即可

今天刚学了java的lambda,正好拿来练练手,写起来确实爽。

class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        if (intervals.size() <= 1) {
            return intervals;
        }
        intervals.sort((e1, e2) -> {
            if (e1.start == e2.start) {
                return Integer.compare(e1.end, e2.end);
            }
            return Integer.compare(e1.start, e2.start);
        });

        List<Interval> ans = new ArrayList<>();
        for (int i = 0; i < intervals.size(); i++) {
            Interval cur = intervals.get(i);
            while (i + 1 < intervals.size()) {
                Interval next = intervals.get(i + 1);
                if (cur.end >= next.start) {
                    cur.end = Math.max(cur.end, next.end);
                    i++;
                } else {
                    break;
                }
            }
            ans.add(cur);
        }

        return ans;
    }
}
posted @ 2018-07-23 22:57 ACBingo 阅读(...) 评论(...) 编辑 收藏