Open nanslee opened 4 years ago
/**
* @param {number[][]} intervals
* @return {number[][]}
*/
var merge = function(intervals) {
let results = [];
let len = intervals.length;
if(len === 0) return [];
intervals.sort((a, b) => a[0] - b[0]);
let i = 0;
while(i < len) {
let currLeft = intervals[i][0];
let currRight = intervals[i][1];
while(i < len - 1 && currRight >= intervals[i + 1][0]) {
i ++;
currRight = Math.max(intervals[i][1], currRight)
}
results.push([currLeft, currRight]);
i++;
}
return results;
};
var merge = function(intervals) {
const arr = []
let now = intervals.shift()
let prev
while (now) {
if (!prev) {
prev = now
continue
}
if (prev[1] >= now[0]) {
prev = [
prev[0] <= now[0] ? prev[0] : now[0],
prev[1] >= now[1] ? prev[1] : now[1]
]
} else {
arr.push(prev)
prev = now
}
now = intervals.shift()
if (!now) {
arr.push(prev)
}
}
return arr
};
var merge = (lists) => {
var res = {}
lists.reduce((a, b) => {
if (b[0] >= a[0] && b[0] <= a[1]) {
var concat = a.concat(b)
var c = [Math.min(...concat), Math.max(...concat)]
res[c] = c
if (res[a]) {
delete res[a]
}
return c
} else {
res[b] = b
return b
}
})
return Object.keys(res).map(i => res[i])
}
merge([[1, 3], [2, 6], [6, 7], [8, 10], [9, 18]])
给出一个区间的集合,请合并所有重叠的区间。