Open windate3411 opened 4 years ago
A+ 題
var merge = function(intervals) {
if (intervals.length < 2) return intervals
intervals.sort((a,b) => {
if(a[0] === b[0]) {
return a[1] - b[1]
} else {
return a[0] - b[0]
}
})
let ans = []
let start = intervals[0][0]
let end = intervals[0][1]
for (let i = 0; i < intervals.length; i++) {
if (intervals[i][0] > end) {
ans.push([start, end])
start = intervals[i][0]
}
if (intervals[i][1] > end) {
end = intervals[i][1]
}
}
ans.push([start, end])
return ans
};
var merge = function(intervals) {
if (intervals.length < 2) return intervals
intervals.sort((a,b) => a[0] - b[0])
let res = []
let start = intervals[0][0]
let end = intervals[0][1]
let i = 1
while(i < intervals.length) {
if (intervals[i][0] > end) {
res.push ([start, end])
start = intervals[i][0]
}
if (intervals[i][1] > end) end = intervals[i][1]
i++
}
res.push([start, end])
return res
};
一口氣一次過的感覺真~爽