-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy path57-insert-interval.js
More file actions
43 lines (41 loc) · 958 Bytes
/
57-insert-interval.js
File metadata and controls
43 lines (41 loc) · 958 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
35
36
37
38
39
40
41
42
43
const hasOverlap = (interval1, interval2) => {
if(interval1[1]<interval2[0] || interval2[1]<interval1[0]) return false
return true
}
/**
* @param {number[][]} intervals
* @param {number[]} newInterval
* @return {number[][]}
*/
var insert = function(intervals, newInterval) {
const res = []
const [lo, hi] = newInterval
let min = lo
let max = hi
let interval
let inserted = false
for(let i=0; i<intervals.length; i++) {
if(inserted) {
res.push(intervals[i])
continue
}
interval = [min, max]
if(!hasOverlap(intervals[i], interval)) {
if(interval[1]<intervals[i][0]) {
res.push(interval)
res.push(intervals[i])
inserted = true
} else {
res.push(intervals[i])
}
} else {
const [currLo, currHi] = intervals[i]
min = Math.min(min, currLo)
max = Math.max(max, currHi)
}
}
if(!inserted) {
res.push([min, max])
}
return res
};