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

代码如下:

 1 /**
 2  * Definition for an interval.
 3  * public class Interval {
 4  *     int start;
 5  *     int end;
 6  *     Interval() { start = 0; end = 0; }
 7  *     Interval(int s, int e) { start = s; end = e; }
 8  * }
 9  */
10 public class Solution {
11     @SuppressWarnings("unchecked")
12     public static List<Interval> partMerge(List<Interval> intervals){
13         intervals.sort(new Comparator(){
14             @Override
15             public int compare(Object o1, Object o2) {
16                 Interval i1 = (Interval)o1;
17                 Interval i2 = (Interval)o2;
18                 if(i1.start!=i2.start)
19                     return i1.start-i2.start;
20                 else
21                     return (Math.abs(i1.end-i1.start)-Math.abs(i2.end-i2.start));
22             }
23         });
24         
25         List<Integer> removeList = new ArrayList<Integer>();
26         for(int i = 0;i < intervals.size()-1; i++ )
27             if(intervals.get(i).end>=intervals.get(i+1).start&&intervals.get(i).end<=intervals.get(i+1).end){
28                     intervals.get(i+1).start = intervals.get(i).start;
29                     removeList.add(i);
30             }else if(intervals.get(i).end>=intervals.get(i+1).end){
31                 intervals.get(i+1).end = intervals.get(i).end;
32                 intervals.get(i+1).start = intervals.get(i).start;
33                 removeList.add(i);
34             }
35         for(int i = removeList.size()-1; i>=0 ; i--){
36             intervals.remove(intervals.get(removeList.get(i)));
37         }
38         return intervals;
39     }
40     public List<Interval> merge(List<Interval> intervals) {
41         int presize = 0;
42         do{
43             presize = intervals.size();
44             intervals = partMerge(intervals);
45         }while(presize!=intervals.size());
46         return intervals;
47     }
48 }

 

posted @ 2017-02-19 10:24  再见,少年  Views(150)  Comments(0Edit  收藏  举报