zoukankan      html  css  js  c++  java
  • 57. Insert Interval

    Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

    You may assume that the intervals were initially sorted according to their start times.

    Example 1:

    Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
    Output: [[1,5],[6,9]]
    

    Example 2:

    Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
    Output: [[1,2],[3,10],[12,16]]
    Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

    NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

    3 cases + edge case at the end
    1. if newInterval.start > curInterval.end (or newInterval is null)
       -> curInterval is valid, insert to list, and leave newInterval to compare with next interval
    2. if newInterval.end < curInterval.start
       -> both valid, add them to list, and set newInterval to be null, which means has been inserted already
    3. other condition, overlap, merge newInterval and curInterval to be a larger interval

    time = O(n), space = O(1)

    class Solution {
        public int[][] insert(int[][] intervals, int[] newInterval) {
            if(intervals.length == 0) {
                return new int[][] {newInterval};
            }
            List<int[]> list = new ArrayList<>();
            for(int i = 0; i < intervals.length; i++) {
                // // non-overlap, current interval valid, leave newInterval to compare with next interval
                if(newInterval == null || newInterval[0] > intervals[i][1]) {
                    list.add(intervals[i]);
                } else if(newInterval[1] < intervals[i][0]) {  // non-overlap, both valid
                    list.add(newInterval);
                    list.add(intervals[i]);
                    newInterval = null;     // newInterval inserted, reset to null
                } else {
                    newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
                    newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
                }
            }
            if(newInterval != null) {   // if newInterval haven't been inserted after traversal, insert at the end
                list.add(newInterval);
            }
            
            int[][] res = new int[list.size()][2];
            for(int i = 0; i < list.size(); i++) {
                res[i] = list.get(i);
            }
            return res;
        }
    }
  • 相关阅读:
    Lua的数学函数
    以KeyValue形式构建Lua Table
    查看占用网速的程序
    JSONObject以及json(转)
    Windows 7 下玩游戏不能全屏
    Windows 7 卸载 IE10
    win7无线网络共享
    打印后台程序服务没有启动,每次打开Powerdesigner都会要我安装打印机
    SQL 条件 判断 select case as
    MyEclipse Web项目调试
  • 原文地址:https://www.cnblogs.com/fatttcat/p/13662471.html
Copyright © 2011-2022 走看看