题解 | #合并区间#
合并区间
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 ) { // write code here if(!intervals.length) return [] let i=1; intervals = intervals.sort((i,c)=>i.start-c.start) const res = [intervals[0]] while(i<intervals.length){ // console.log(res) if(res[res.length-1].end >= intervals[i].start){ // console.log("--",intervals[i]) res[res.length-1].end = Math.max(intervals[i].end,res[res.length-1].end); i++ // console.log(JSON.stringify(res)) continue; } res.push(intervals[i]) i++ } return res } module.exports = { merge : merge };