Voyz's Studio.

LeetCode算法笔记--合并区间

字数统计: 144阅读时长: 1 min
2020/12/17 Share

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
/**
* @param {number[][]} intervals
* @return {number[][]}
*/
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;
};
CATALOG
  1. 1. LeetCode算法笔记–Day44
  2. 2. 56. Merge Intervals
    1. 2.1. 题目:
    2. 2.2. My Answer: