首页 > 其他 > 详细

LeetCode: Merge Intervals

时间:2014-03-17 10:39:35      阅读:466      评论:0      收藏:0      [点我收藏+]

comparator的写法。

Collections.sort与Arrays.sort的区别。

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

都可以使用comparator。

 

bubuko.com,布布扣
 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 }
bubuko.com,布布扣

LeetCode: Merge Intervals,布布扣,bubuko.com

LeetCode: Merge Intervals

原文:http://www.cnblogs.com/longhorn/p/3604232.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!