题解 | #合并区间#
合并区间
http://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 ) {
// write code here
if(intervals.length===0) return [];
const res=[];
intervals.sort(function(a,b){
return a.start-b.start
})
let prev=intervals[0];
for(let i=1;i<intervals.length;i++){
const cur=intervals[i];
let left = cur.start;
let right= cur.end;
if(prev.end>=left){
prev.end = Math.max(prev.end,cur.end);
}else {
res.push(new Interval(prev.start,prev.end));
prev=cur;
}
}
res.push(prev)
return res;
}
module.exports = {
merge : merge
};