56. Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]Output: [[1,6],[8,10],[15,18]]Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]Output: [[1,5]]Explanation: Intervals [1,4] and [4,5] are considered overlapping. 题意:将重叠的区间的两个数组合并, 代码如下:
/** * Definition for an interval. * function Interval(start, end) { * this.start = start; * this.end = end; * } *//** * @param {Interval[]} intervals * @return {Interval[]} */var merge = function(intervals) { if(intervals.length===0 || intervals===null) return intervals; var res=[]; intervals.sort(function(a,b){ return a.start-b.start; }) res.push(intervals[0]); for(var i=1;ires[res.length-1].end){ res.push(intervals[i]); }else{ res[res.length-1].end=Math.max(intervals[i].end,res[res.length-1].end); } } return res; };