-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproblem_077.js
More file actions
34 lines (29 loc) Β· 804 Bytes
/
problem_077.js
File metadata and controls
34 lines (29 loc) Β· 804 Bytes
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
// https://leetcode.com/problems/merge-intervals/
//
// O(N Log N) Time complexity
// O(1) Space complexity
/**
* Returns a new list of intervals where all overlapping intervals have been merged
* @param {number[][]} arr
* @return {number[][]}
*/
function mergearr(arr) {
if (arr.length === 0 || arr.length === 1) return arr;
// Sort arr by their start
arr.sort((a, b) => a[0] - b[0]);
const merged = [];
let curr = arr[0];
for (let i = 1; i < arr.length; i++) {
const [currStart, currEnd] = curr;
const [arrtart, arrEnd] = arr[i];
if (arrtart <= currEnd) {
// merge and make curr
curr = [currStart, Math.max(currEnd, arrEnd)];
} else {
merged.push([currStart, currEnd]);
curr = intervals[i];
}
}
merged.push(curr);
return merged;
}