首页 > 其他 > 详细

Merge Intervals

时间:2015-11-16 22:43:35      阅读:306      评论:0      收藏:0      [点我收藏+]

1. Title

Merge Intervals

2. Http address

https://leetcode.com/problems/merge-intervals/

3. The question

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

4 My code(AC)

  •  
     1 // Accepted
     2       public static List<Interval> merge(List<Interval> intervals) {
     3          
     4           List<Interval> res = new ArrayList<Interval>();
     5           if ( intervals == null || intervals.isEmpty() )
     6               return res;
     7           
     8           Comparator<Interval> com = new Comparator<Interval>(){
     9                   public int compare(Interval a ,Interval b)
    10                   {
    11                       if ( a.start < b.start) return -1;
    12                       else if ( a.start > b.start ) return 1;
    13                       else {
    14                           if ( a.end < b.end) return -1;
    15                           else if ( a.end > b.end ) return 1;
    16                           else return 0;
    17                       }
    18                   }
    19           };
    20           
    21           Collections.sort(intervals,com);
    22           
    23           for( int i = 0 ; i < intervals.size(); i++)
    24           {
    25               Interval cur = intervals.get(i);
    26               if ( res.isEmpty() )
    27               {
    28                   res.add(cur);
    29               }else{
    30                   Interval last = res.get(res.size() - 1);
    31                   if ( last.end >= cur.start)
    32                   {
    33                       last.end = Math.max(last.end, cur.end);
    34                   }else{
    35                       res.add(cur);
    36                   }
    37               }
    38           }
    39           return res;
    40         }
    41       

     

Merge Intervals

原文:http://www.cnblogs.com/ordili/p/4970052.html

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