Skip to content
On this page

57. 插入区间

给你一个 无重叠的 ,按照区间起始端点排序的区间列表。
在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。

示例 1:
输入:intervals = [[1,3],[6,9]], newInterval = [2,5]
输出:[[1,5],[6,9]]

示例 2:
输入:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
输出:[[1,2],[3,10],[12,16]]
解释:这是因为新的区间 [4,8] 与 [3,5],[6,7],[8,10] 重叠。

示例 3:
输入:intervals = [], newInterval = [5,7]
输出:[[5,7]]

示例 4:
输入:intervals = [[1,5]], newInterval = [2,3]
输出:[[1,5]]

示例 5:
输入:intervals = [[1,5]], newInterval = [2,7]
输出:[[1,7]]

提示:
0 <= intervals.length <= 104
intervals[i].length == 2
0 <= intervals[i][0] <= intervals[i][1] <= 105
intervals 根据 intervals[i][0] 按 升序 排列
newInterval.length == 2
0 <= newInterval[0] <= newInterval[1] <= 105

javascript
/**
 * @param {number[][]} intervals
 * @param {number[]} newInterval
 * @return {number[][]}
 */
var insert = function(intervals, newInterval) {
  intervals.push(newInterval)
  intervals.sort((a, b) => a[0] - b[0])
  let j = 0
  while(j < intervals.length - 1){
    const [preStart, preEnd] = intervals[j], [nextStart, nextEnd] = intervals[j + 1]
    if(preEnd < nextStart || preStart > nextEnd){
      j++
    }else {
      const start = Math.min(preStart, nextStart), end = Math.max(preEnd, nextEnd)
      intervals.splice(j, 2, [start, end])
    }
  }
  return intervals
}

console.log(insert([[1,3],[6,9]], [2,5]))
console.log(insert([[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8]))
console.log(insert([], [5,7]))
console.log(insert([[1,5]], [2,3]))
console.log(insert([[1,5]], [2,7]))
console.log(insert([[1,5],[6,8]],[0,9]))
console.log(insert([[1,5],[6,8]],[8,10]))