题解 | #合并区间#
合并区间
https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
/*
* function Interval(a, b){
* this.start = a || 0;
* this.end = b || 0;
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param intervals Interval类一维数组
* @return Interval类一维数组
*/
function merge(intervals) {
const res = [];
//排序左区间,对比右区间
intervals.sort((a, b) => a.start - b.start);
//对比每个区间
for (let i = 0; i < intervals.length; i++) {
const L = intervals[i].start;
const R = intervals[i].end;
if (res.length === 0 || res[res.length - 1].end < L) {
res.push(new Interval(L, R));
} else {
res[res.length - 1].end = Math.max(res[res.length - 1].end, R);
}
}
return res;
}
module.exports = {
merge: merge,
};
如果我们按照区间的左端点排序,那么在排完序的列表中,可以合并的区间一定是连续的。