Merge Intervals

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       
原文地址:https://www.cnblogs.com/ordili/p/4970052.html