/*
* function Interval(a, b){
* this.start = a || 0;
* this.end = b || 0;
* }
*/
/**
*
* @param intervals Interval类一维数组
* @return Interval类一维数组
*/
function merge( intervals ) {
if (intervals.length<2) return intervals;
intervals.sort((a, b) => a.start - b.start);
let res = [],cur=intervals[0];
for (let i = 1; i < intervals.length; i++) {
let last = intervals[i];
if (last.start <= cur.end) {
cur.end=Math.max(cur.end,last.end) //必须比较:如[10,30][20,24]
}
else {
res.push(cur);
cur=last;
}
}
if(cur){
res.push(cur);
}
return res;
}
module.exports = {
merge : merge
};
合并区间
最新推荐文章于 2021-08-31 11:06:37 发布