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

57 Insert Interval

时间:2018-08-10 15:53:01      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:dex   you   github   https   find   pac   public   zhang   for   

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

标签:dex   you   github   https   find   pac   public   zhang   for   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9454895.html

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