-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert-interval.js
37 lines (31 loc) · 1015 Bytes
/
insert-interval.js
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
/**
* @param {number[][]} intervals
* @param {number[]} newInterval
* @return {number[][]}
*/
var insert = function(intervals, newInterval) {
if (!intervals) return [];
const ans = new Array();
intervals.push(newInterval);
intervals.sort((a, b) => a[0] - b[0]);
if (intervals.length === 1) return intervals;
const prev = [intervals[0][0], intervals[0][1]];
for (let i = 1; i < intervals.length; i++) {
const curr = intervals[i];
if (isOverlap(prev, curr)) {
prev[0] = Math.min(prev[0], curr[0]);
prev[1] = Math.max(prev[1], curr[1]);
} else {
ans.push([...prev]);
prev[0] = curr[0];
prev[1] = curr[1];
}
if (i === intervals.length - 1) ans.push([...prev])
}
return ans;
};
const isOverlap = (prev, curr) => {
return prev[1] >= curr[0] && prev[1] <= curr[1] ||
prev[0] >= curr[0] && prev[0] <= curr[1] ||
prev[0] <= curr[0] && prev[1] >= curr[1];
};