-
Notifications
You must be signed in to change notification settings - Fork 1
/
56.合并区间.ts
47 lines (41 loc) · 909 Bytes
/
56.合并区间.ts
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
* @lc app=leetcode.cn id=56 lang=typescript
*
* [56] 合并区间
*/
// @lc code=start
function merge(intervals: number[][]): number[][] {
const ans: number[][] = [];
intervals.sort((a, b) => a[0] - b[0]);
for (let left = 0; left < intervals.length; left++) {
// eslint-disable-next-line prefer-const
let [leftStart, leftEnd] = intervals[left];
for (let right = left + 1; right < intervals.length; right++) {
const [rightStart, rightEnd] = intervals[right];
if (rightStart <= leftEnd) {
leftEnd = Math.max(leftEnd, rightEnd);
left++;
}
if (rightStart > leftEnd) {
break;
}
}
ans.push([leftStart, leftEnd]);
}
return ans;
}
// @lc code=end
test("merge", () => {
expect(
merge([
[1, 3],
[2, 6],
[8, 10],
[15, 18],
])
).toEqual([
[1, 6],
[8, 10],
[15, 18],
]);
});