Merge Intervals

来源:互联网 发布:mysql如何导出数据库 编辑:程序博客网 时间:2024/06/11 13:28

学会,熟练用排序,不要犯傻傻的错误。

联系会议室问题。

/** * 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; } * } */public class Solution {    public List<Interval> merge(List<Interval> intervals) {        List<Interval> res = new LinkedList<>();        if (intervals == null) {            throw new IllegalArgumentException("haha");        }        if (intervals.size() == 0) {            return res;        }        //Arrays.sort(intervals, new Comporator<Interval>() {        Collections.sort(intervals, new Comparator<Interval>() {            @Override            public int compare(Interval i1, Interval i2) {                if (i1.start != i2.start) {                    return i1.start - i2.start;                } else {                    return i1.end - i2.end;                }            }        });        Interval prev = intervals.get(0);        for (int i = 0; i < intervals.size(); i++) {            Interval cur = intervals.get(i);            if (cur.start > prev.end) {                res.add(prev);                prev = cur;            } else {                Interval merge = new Interval(prev.start, Math.max(prev.end, cur.end));                prev = merge;            }        }        res.add(prev);        return res;    }}

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



0 0