56-Merge Intervals

【题目】

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

【analyze】

1.需要先根据每个Interval的start进行排序

2.再根据pre的end是否大于等于cur的start来判断,是否需要进行合并

【算法】

/**
 * 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) {
        if(intervals==null||intervals.size()<1)
            return intervals;
        Collections.sort(intervals,new Comparator<Interval>() {
            public int compare(Interval i1,Interval i2) {
                return i1.start-i2.start;
            }});
            
        List<Interval> res=new ArrayList<Interval>();
        Interval pre=intervals.get(0);
        for(int i=1;i<intervals.size();i++) {
            Interval cur=intervals.get(i);
            if(pre.end>=cur.start) {
                Interval merge=new Interval(pre.start,Math.max(pre.end,cur.end));
                pre=merge;
            }else {
                res.add(pre);
                pre=cur;
            }
        }
        res.add(pre);
        return res;
    }
}

 

posted @ 2015-05-05 15:32  hwu_harry  阅读(77)  评论(0编辑  收藏  举报