Open sisterAn opened 4 years ago
待更新
let merge = (intervals) => {
const len = intervals.length;
if (len === 0) return [];
// 排序
intervals.sort((s1, s2) => {
return s1[0] - s2[0];
})
let arr = [];
arr.push(intervals[0]);
for (let i = 1; i < len; i++) {
const arrLen = arr.length;
if (intervals[i][0] < arr[arrLen - 1][1]) {
arr[arrLen - 1][1] = intervals[i][1] > arr[arrLen - 1][1] ? intervals[i][1] : arr[arrLen - 1][1];
} else {
arr.push(intervals[i]);
}
}
return arr
}
function merge(arr) {
arr.sort((a, b) => a[0] - b [0])
for(let i = 0 ; i < arr.length - 1; i++) {
let a2 = arr[i][1]
let b1 = arr[i+1][0]
let b2 = arr[i+1][1]
if(a2 >= b1) {
arr[i][1] = a2 >= b2 ? a2 : b2
arr.splice(i+1, 1)
i--
}
}
console.log('arr', arr)
return arr
}
let arr = [[1,3],[2,6],[8,10],[15,18]]
merge(arr)``
var merge = function(intervals) {
// 判断空数组
if(intervals.length===0) return []
// 以数组第一位升序排序
intervals.sort((a,b)=>a[0]-b[0])
let j = 1
// 初始化结果数组
let res = [intervals[0]]
while(j<intervals.length){
// 如果遍历数组和结果数组最后一位无交集,直接放到结果集中
if(intervals[j][0]>res[res.length-1][1]){
res.push(intervals[j])
// 有交集时,更新结果集最后一位的最大值
}else{
res[res.length-1][1] = Math.max(res[res.length-1][1],intervals[j][1])
}
j++
}
return res
};
var merge = function(intervals) { let res = [] let len = intervals.length; if(len === 0) return res; intervals.sort((a, b) => a[0] - b[0]); for(let i = 0; i < len; i++){ let curr = intervals[i] if(res.length && res[res.length-1][1] >= curr[0]){ res[res.length-1][1] = Math.max(res[res.length-1][1], curr[1]) }else{ res.push(curr) } } return res };
给出一个区间的集合,请合并所有重叠的区间。
示例 1:
示例 2:
提示:
intervals[i][0] <= intervals[i][1]
leetcode地址