056 Merge Intervals 合并区间

给出一个区间的集合, 请合并所有重叠的区间。
示例:
给出 [1,3],[2,6],[8,10],[15,18],
返回 [1,6],[8,10],[15,18].
详见:https://leetcode.com/problems/merge-intervals/description/

Java实现:

/**
 * 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<Interval> merge(List<Interval> intervals) {
        List<Interval> res=new LinkedList<Interval>();
        int size=intervals.size();
        if(intervals==null||size==0){
            return res;
        }
        Collections.sort(intervals,new Comparator<Interval>(){
            @Override
            public int compare(Interval o1,Interval o2){
                if(o1.start<o2.start){
                    return -1;
                }else if(o1.start>o2.start){
                    return 1;
                }else{
                    return 0;
                }
            }
        });
        res.add(intervals.get(0));
        for(int i=1;i<size;++i){
            Interval cur=intervals.get(i);
            Interval top=res.get(res.size()-1);
            if(top.end>=cur.start){
                top.end=top.end>cur.end?top.end:cur.end;
            }else{
                res.add(cur);
            }
        }
        return res;
    }
}

参考:https://blog.csdn.net/zdavb/article/details/47252657 

posted on 2018-04-02 22:42  lina2014  阅读(137)  评论(0编辑  收藏  举报

导航