LeetCode算法笔记–Day44
56. Merge Intervals
题目:
Given a collection of intervals, merge all overlapping intervals.
example
input: intervals = [[1,3],[2,6],[8,10],[15,18]]
output: [[1,6],[8,10],[15,18]]
input: intervals = [[4,5],[1,4]]
output: [[1,5]]
My Answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
var merge = function(intervals) { if(intervals.length <= 1) return intervals;
intervals.sort(function(a,b){ return a[0]-b[0] })
let res = [], new_interval = intervals[0], point = 1;
while(point <= intervals.length){ if(!!intervals[point] && intervals[point][0] <= new_interval[1]){ new_interval = [Math.min(intervals[point][0], new_interval[0]),Math.max(intervals[point][1], new_interval[1])]; }else{ res.push(new_interval); new_interval = intervals[point]; } point ++; }
return res; };
|