-
Notifications
You must be signed in to change notification settings - Fork 0
/
57.insert-interval.js
63 lines (53 loc) · 1.49 KB
/
57.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
* @lc app=leetcode id=57 lang=javascript
*
* [57] Insert Interval
*/
// @lc code=start
/**
* @param {number[][]} intervals
* @param {number[]} newInterval
* @return {number[][]}
*/
var insert_v1 = function (intervals, newInterval) {
let leftIntervals = [];
let rightIntervals = [];
let start = newInterval[0];
let end = newInterval[1];
for (let i = 0; i < intervals.length; i += 1) {
if (newInterval[1] < intervals[i][0]) {
// new interval is smaller without overlapping
rightIntervals.push(intervals[i]);
} else if (intervals[i][1] < newInterval[0]) {
// current interval is smaller without overlapping
leftIntervals.push(intervals[i]);
} else {
// overlapping
start = Math.min(intervals[i][0], start);
end = Math.max(intervals[i][1], end);
}
}
return [...leftIntervals, [start, end], ...rightIntervals];
};
var insert = function (intervals, newInterval) {
if (!intervals.length) return [newInterval];
let results = [];
let curInterval = newInterval;
for (let i = 0; i < intervals.length; i++) {
if (curInterval[1] < intervals[i][0]) {
results.push(curInterval, ...intervals.slice(i));
return results;
}
if (curInterval[0] > intervals[i][1]) {
results.push(intervals[i]);
} else {
curInterval = [
Math.min(curInterval[0], intervals[i][0]),
Math.max(curInterval[1], intervals[i][1]),
];
}
}
results.push(curInterval);
return results;
};
// @lc code=end