-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode57.js
60 lines (55 loc) · 1.38 KB
/
leetcode57.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* @param {number[][]} intervals
* @param {number[]} newInterval
* @return {number[][]}
* https://leetcode.com/problems/insert-interval/
* https://leetcode.com/submissions/detail/545852612/
*/
var insert = function (intervals, newInterval) {
if (intervals.length === 0) {
return [newInterval];
}
let lowerBoundIndex;
let upperBoundIndex;
let smallNew = newInterval[0];
let largeNew = newInterval[1];
for (let i = 0; i < intervals.length; i++) {
if (
smallNew <= intervals[i][0] ||
(smallNew > intervals[i][0] && smallNew <= intervals[i][1])
) {
if (lowerBoundIndex === undefined) {
lowerBoundIndex = i;
}
}
if (largeNew >= intervals[i][1] || largeNew >= intervals[i][0]) {
upperBoundIndex = i;
}
}
// return [lowerBoundIndex, upperBoundIndex];
if (lowerBoundIndex === undefined) {
intervals.push(newInterval);
return intervals;
}
if (upperBoundIndex === undefined) {
return [newInterval, ...intervals];
}
return [
...intervals.slice(0, lowerBoundIndex),
[
Math.min(
intervals[lowerBoundIndex][0],
intervals[lowerBoundIndex][1],
smallNew,
largeNew
),
Math.max(
intervals[upperBoundIndex][0],
intervals[upperBoundIndex][1],
smallNew,
largeNew
),
],
...intervals.slice(upperBoundIndex + 1),
];
};