zoukankan      html  css  js  c++  java
  • [LintCode] Insert Interval

    Given a non-overlapping interval list which is sorted by start point.

    Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).

    Example

    Insert [2, 5] into [[1,2], [5,9]], we get [[1,9]].

    Insert [3, 4] into [[1,2], [5,9]], we get [[1,2], [3,4], [5,9]].

    Algorithm: 

    Iterate over the original interval list one by one and keep an insertion position for the new interval.

    Case 1: newInterval is after the current interval:  If the current interval's end < newInterval's start, insert the current interval to the new list, increment the insertion position by 1.

    Case 2: newInterval is before the current interval: Else if the current interval's start > newInterval's end, insert the current interval to the new list. 

    Case 3: newInterval overlaps with the current interval. Update the newInterval's start and end to cover both intervals. 

    Repeat the above steps until all intervals in the original list are processed. 

    Finally, insert the newInterval to the saved insertion position. 

     1 /**
     2  * Definition of Interval:
     3  * public classs Interval {
     4  *     int start, end;
     5  *     Interval(int start, int end) {
     6  *         this.start = start;
     7  *         this.end = end;
     8  *     }
     9  */
    10 public class Solution {
    11     public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
    12         if (newInterval == null) {
    13             return intervals;
    14         }
    15         ArrayList<Interval> results = new ArrayList<Interval>();
    16         if(intervals == null) {
    17             results.add(newInterval);
    18             return results;
    19         }
    20         int insertPos = 0;
    21         for (Interval interval : intervals) {
    22             if (interval.end < newInterval.start) {
    23                 results.add(interval);
    24                 insertPos++;
    25             } else if (interval.start > newInterval.end) {
    26                 results.add(interval);
    27             } else {
    28                 newInterval.start = Math.min(interval.start, newInterval.start);
    29                 newInterval.end = Math.max(interval.end, newInterval.end);
    30             }
    31         }
    32         results.add(insertPos, newInterval);
    33         return results;
    34     }
    35 }

    Related Problems 

    Merge Intervals

  • 相关阅读:
    【Node】fs
    ☀【滚动条】动画,固定
    洛谷——P3817 小A的糖果
    洛谷——P1316 丢瓶盖
    洛谷—— P1190 接水问题
    CODEVS——T1332 上白泽慧音 || 洛谷——P1726 上白泽慧音
    CODEVS——T3008 加工生产调度
    python(20)- 列表生成式和生成器表达式练习Ⅱ
    MTK Android 编译命令
    第六届深圳国际物联网和智慧中国博览会(2014)总结
  • 原文地址:https://www.cnblogs.com/lz87/p/7169574.html
Copyright © 2011-2022 走看看