码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Merge Intervals

时间:2014-11-13 01:51:28      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   sp   for   div   on   

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

 

Solution:

 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     static public class MyCompare implements Comparator<Interval> {
12         @Override
13         public int compare(Interval o1, Interval o2) {
14             // TODO Auto-generated method stub
15             if (o1.start != o2.start)
16                 return o1.start < o2.start ? -1 : 1;
17             else if (o1.end != o2.end)
18                 return o1.end < o2.end ? -1 : 1;
19             else
20                 return 0;
21         }
22     }
23 
24     public List<Interval> merge(List<Interval> intervals) {
25         List<Interval> result = new ArrayList<Interval>();
26         
27         if (intervals.size() == 0)
28             return result;
29         if (intervals.size() == 1)
30             return intervals;
31         
32         Collections.sort(intervals, new MyCompare());
33         Interval last=intervals.get(0);
34         int N=intervals.size();
35         for(int i=1;i<N;++i){
36             if(intervals.get(i).start>last.end){
37                 result.add(new Interval(last.start,last.end));
38                 last=intervals.get(i);
39             }else{
40                 last.end=Math.max(intervals.get(i).end, last.end);
41             }
42         }
43         result.add(last);
44         return result;
45     }
46 }

 

[Leetcode] Merge Intervals

标签:style   blog   io   color   ar   sp   for   div   on   

原文地址:http://www.cnblogs.com/Phoebe815/p/4093943.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!