Merge Intervals

来源:互联网 发布:ie11 找不到js 编辑:程序博客网 时间:2024/06/11 07:30
/** * 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(" ");        }        if (intervals.size() == 0) {            return res;        }        Collections.sort(intervals, new Comparator<Interval>(){            @Override            public int compare(Interval a, Interval b) {                if (a.start != b.start) {                    return a.start - b.start;                } else {                    return a.end - b.end;                }            }        });        Interval prev = intervals.get(0);        for (int i = 1; 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, Integer.max(prev.end, cur.end));                prev = merge;            }        }        res.add(prev);        return res;    }}

0 0
原创粉丝点击