Appearance
56. 合并区间
以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。
示例 1:
输入:intervals = [[1,3],[2,6],[8,10],[15,18]]
输出:[[1,6],[8,10],[15,18]]
解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例 2:
输入:intervals = [[1,4],[4,5]]
输出:[[1,5]]
解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。
提示:
1 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 104
- 来源:力扣(LeetCode)
- 链接:https://leetcode.cn/problems/merge-intervals
javascript
/**
* @param {number[][]} intervals
* @return {number[][]}
*/
var merge = function(intervals) {
intervals.sort((a, b) => a[0] - b[0])
let i = 0
while(i < intervals.length - 1){
const [preStart, preEnd] = intervals[i], [nextStart, nextEnd] = intervals[i + 1]
if(preEnd < nextStart || preStart > nextEnd){
i++
}else {
const start = Math.min(preStart, nextStart), end = Math.max(preEnd, nextEnd)
intervals.splice(i, 2, [start, end])
}
}
return intervals
}
console.log(merge([[1,3],[2,6],[8,10],[15,18]]))
console.log(merge([[1,4],[4,5]]))
console.log(merge([[2,3],[4,5],[6,7],[8,9],[1,10]]))
console.log(merge([[1,4],[0,2],[3,5]]))
console.log(merge([[2,3],[5,5],[2,2],[3,4],[3,4]]))