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

LeetCode Merge Intervals

时间:2015-01-16 23:33:59      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

LeetCode Merge Intervals

标签:

原文地址:http://www.cnblogs.com/birdhack/p/4229898.html

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