57 Insert Interval

Posted tobeabetterpig

tags:

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

57 Insert Interval


https://www.youtube.com/watch?v=oWHWDI2eOHY


Sol1: use 56, insert this new interval into the sorted list, since its sorted already
No need to sort it again, so the time complexiy is o(n), for merging 
Space is still o(n)

class Solution {
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
      // find the right index to insert the new interval into the intervals 
      int s = newInterval.start;
      int index = 0;
      for(Interval interval : intervals){
        if (interval.start <= s){
          index++;
        }
      }
      intervals.add(index, newInterval);
      
      List<Interval> result = new ArrayList<>();
      int start = intervals.get(0).start;
      int end = intervals.get(0).end;
      
      for(Interval interval : intervals){
        if(interval.start <= end){
          end = Math.max(end, interval.end);
        }else{
          result.add(new Interval(start, end));
          start = interval.start;
          end = interval.end;
        }
      }
      result.add(new Interval(start, end));
      return result;
    }
}








Sol2: 

很多人都用这个方法, 很多用while 写
我觉得用 if else 写 清楚
7:52 参考花花的代码

class Solution {
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
      List<Interval> left = new ArrayList<>();
      List<Interval> right = new ArrayList<>();
      
      int start = newInterval.start;
      int end = newInterval.end;
      
      for(Interval interval : intervals){
        if(interval.end < start){
          left.add(interval);
        }else if(interval.start > end){
          right.add(interval);
        }else{
          start = Math.min(start, interval.start);
          end = Math.max(end, interval.end);
        }
      }
      
      List<Interval> result = new ArrayList<>();
      for(Interval interval : left){
        result.add(interval);
      }
      
      result.add(new Interval(start, end));
      
      for(Interval interval : right){
        result.add(interval);
      }
      return result;
    }
}

https://github.com/tongzhang1994/Facebook-Interview-Coding/blob/master/57.%20Insert%20Interval.java

 

以上是关于57 Insert Interval的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode57 Insert Interval

57. Insert Interval

57. Insert Interval

57. Insert Interval

57. Insert Interval

57. Insert Interval