0057. Insert Intervals (H)

Insert Interval (H)

题目

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].

题意

给定一个左端点递增且互不重叠的区间数组,向其中插入一个新的区间,如有重叠则需要合并,返回处理后的区间数组。

思路

先将所有右端点在新区间左端点之前的区间(即一定不会相交)插入到结果中,再将所有可以与新区间合并的区间进行合并,并加入到结果中,最后将剩余一部分不会合并的区间加入到结果中。


代码实现

Java

class Solution {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> list = new ArrayList<>();
        int i = 0;
        while (i < intervals.length && intervals[i][1] < newInterval[0]) {
            list.add(intervals[i++]);
        }
        while (i < intervals.length && intervals[i][0] <= newInterval[1] && intervals[i][1] >= newInterval[0]) {
            newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
            newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
            i++;
        }
        list.add(newInterval);
        while (i < intervals.length) {
            list.add(intervals[i++]);
        }

        return list.toArray(new int[0][]);
    }
}

JavaScript

/**
 * @param {number[][]} intervals
 * @param {number[]} newInterval
 * @return {number[][]}
 */
var insert = function (intervals, newInterval) {
  let ans = []
  let i = 0

  while (i < intervals.length && intervals[i][1] < newInterval[0]) {
    ans.push(intervals[i++])
  }

  let left = newInterval[0]
  let right = newInterval[1]
  while (i < intervals.length && intervals[i][0] <= right && intervals[i][1] >= left) {
    left = Math.min(intervals[i][0], left)
    right = Math.max(intervals[i][1], right)
    i++
  }
  ans.push([left, right])

  while (i < intervals.length) {
    ans.push(intervals[i++])
  }

  return ans
}
posted @ 2020-07-05 03:33  墨云黑  阅读(179)  评论(0编辑  收藏  举报