[leedcode 57] 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].

/**
 * 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) {
        //采用的是和Insert Interval一样的思想,只不过最开头要先排序一下,用到了java的Collections.sort(List<Interval> list, Comparator<? super Interval> c)
        //需要自己实现了一个Comparator的compare方法
        //注意compare的实现方式!!
        //因为已经排过序,并且是从头开始遍历,因此不会出现后面遍历的在temp之前的情况,所以注释部分可有可无
        List<Interval> res=new ArrayList<Interval>();
        if(intervals.size()<1) return res;
        Collections.sort(intervals,new IntervalCom());///
        Interval temp=intervals.get(0);
        for(int i=1;i<intervals.size();i++){
            Interval cur=intervals.get(i);
           /* if(cur.end<temp.start){
                //res.add(cur);
            }else{*/
                if(cur.start>temp.end){
                    res.add(temp);
                    temp=cur;
                }else{
                    int start=Math.min(temp.start,cur.start);
                    int end=Math.max(temp.end,cur.end);
                    temp=new Interval(start,end);
                }
            //}
            
        }
        res.add(temp);
        return res;
        
    }
    public class IntervalCom implements Comparator<Interval>{////
        public int compare(Interval o1,Interval o2){
            return o1.start-o2.start;
        }
    }
}

 

你可能感兴趣的:(merge)