LeetCode 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  class intervalComparator implements Comparator<Interval>{
11     @Override
12     public int compare(Interval o1, Interval o2) {
13         return o1.start-o2.start;
14     }
15 }
16 public class Solution {
17     public List<Interval> merge(List<Interval> intervals) {
18         List<Interval> result = new ArrayList<Interval>();
19         if (intervals.size() == 0) {
20             return result;
21         }
22         Collections.sort(intervals, new intervalComparator());
23         Interval first = intervals.get(0);
24         Interval next;
25         for (int i = 1; i <intervals.size() ; i++) {
26             next = intervals.get(i);
27             if (first.end < next.start) {
28                 result.add(first);
29                 first = next;
30             } else {
31                 if (first.end < next.end) {
32                     first.end = next.end;
33                 } 
34             }
35         }
36         result.add(first);
37         return result;
38     }
39 }

 

posted @ 2015-01-16 22:40  birdhack  阅读(84)  评论(0编辑  收藏  举报