原题
区间为 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] 可被视为重叠区间。
题解
var merge = function(intervals) {
let res = []
for (let i = 0; i < intervals.length; i++) {
let len = intervals.length - i - 1;
for (let j = 0; j < len; j++) {
if (intervals[j + 1][1] < intervals[j][1]) {
let tmp = intervals[j+1];
intervals[j+1] = intervals[j];
intervals[j] = tmp;
}
}
if(res[0] && res[res.length-1][0] <= intervals[len][1]) {
res[res.length-1][0] = Math.min(res[res.length-1][0], intervals[len][0]);
} else {
res.push(intervals[len])
}
}
return res;
};
var merge = function(intervals) {
let res = [];
let strat = [];
let end = [];
for(let i = 0; i < intervals.length; i++) {
strat.push(intervals[i][0]);
end.push(intervals[i][1]);
}
strat.sort((a, b) => a - b);
end.sort((a, b) => a - b);
for(let i = 0, j = 0; i < intervals.length; i++) {
if(i == intervals.length - 1 || strat[i+1] > end[i]) {
res.push([strat[j], end[i]]);
j = i + 1;
}
}
return res;
};
|