LeetCode: Merge Intervals

comparator的写法。

Collections.sort与Arrays.sort的区别。

Arrays.sort只应用于arrays。LinkedList,ArrayList要用collections.sort。

都可以使用comparator。

 

 1 public class Solution {
 2     public static ArrayList<Interval> merge(ArrayList<Interval> intervals) {
 3         ArrayList<Interval> result = new ArrayList<Interval>();
 4         if (intervals.size() == 0) return result;
 5         Collections.sort(intervals, new comparator());
 6         
 7         result.add(intervals.get(0));
 8         
 9         for (int i=1; i<intervals.size(); i++) {
10             Interval in = intervals.get(i);
11             Interval last = result.get(result.size()-1);
12             
13             if (in.start<=last.end) {
14                 if (in.end > last.end)
15                     last.end = in.end;
16             }
17             else {
18                 result.add(in);
19             }
20         }
21         
22         return result;
23     }
24     
25     static class comparator implements Comparator<Interval> {
26         public int compare(Interval a, Interval b) {
27             // TODO Auto-generated method stub
28             return a.start - b.start;
29         }
30     }
31 }

 

posted on 2014-03-17 02:39  longhorn  阅读(139)  评论(0编辑  收藏  举报

导航