LeetCode56 合并区间

前后两区间连的上(pre.end>=cur.start)则只用更新pre.end,连不上就添加区间

public List merge(List intervals) {
        if(intervals == null || intervals.size() == 0) return new ArrayList();
        Collections.sort(intervals,new Comparator(){
            public int compare (Interval i1, Interval i2){
                return i1.start - i2.start;
            }
        });
        List list = new LinkedList<>();
        Interval pre = new Interval(intervals.get(0).start,intervals.get(0).end);
        for(Interval curr: intervals){
            if(pre.end < curr.start) {
                list.add(pre);
                pre = curr;
            }else {
                pre.end = Math.max(pre.end, curr.end);
            }
        }
        list.add(pre);
        return list;
    }

你可能感兴趣的:(LeetCode56 合并区间)