56. Merge Intervals

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了56. Merge Intervals相关的知识,希望对你有一定的参考价值。

56. Merge Intervals
https://www.youtube.com/watch?v=6tLHjei-f0I
这个就是 sweep line 

Time nlogn sorting and o(n) for merge 
So nlogn in total

Space o(n) if no overlapping intervals 
https://github.com/tongzhang1994/Facebook-Interview-Coding/blob/master/56.%20Merge%20Intervals.java


注意:1.别忘先sort 2.中间用if-else 3.loop后别忘add最后一个interval


  // sort the intervals by starting time first 
      
      // take the first interval , and compare with the second 
      // interval 
      
      // and check if the second interval  starts before the 
      // first interval ends, if yes, take the max of their end as the end 
      // of the first interval. 
      
      //if no overlap, then add the first interval into the 
      // result, and move onto the second interval inorder to compare with the rest 
      
      



/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
class Solution {
    public List<Interval> merge(List<Interval> intervals) {
      if(intervals.size() <= 1){
        return intervals;
      }
      
      // Collections.sort(), not Arrays.sort()
      Collections.sort(intervals, new Comparator<Interval>(){
        @Override
        public int compare(Interval i1, Interval i2){
          if(i1.start < i2.start){
            return -1;
          }else if( i1.start > i2.start){
            return 1;
          }else{
            return 0;
          }
      });
        
      int start = intervals.get(0).start;
      int end = intervals.get(0).end;
        
      List<Interval> result = new ArrayList<>();
        
      for(Interval interval : intervals){
        if(interval.start <= end){
          end = Math.max(interval.end, end);
        }else{
          result.add(new Interval(start, end));
          start = interval.start;
          end = interval.end;
        }
      }
      result.add(new Interval(start, end));
      return result;
      }
} 
     

 

以上是关于56. Merge Intervals的主要内容,如果未能解决你的问题,请参考以下文章

56. Merge Intervals

Leetcode 56. Merge Intervals

#Leetcode# 56. Merge Intervals

56. Merge Intervals - LeetCode

56. Merge Intervals

#56 Merge intervals