-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFind Right Interval.js
More file actions
41 lines (33 loc) · 934 Bytes
/
Find Right Interval.js
File metadata and controls
41 lines (33 loc) · 934 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
function findRightInterval(intervals) {
const n = intervals.length;
let starts = [];
for (let i = 0; i < n; i++) {
starts.push([intervals[i][0], i]);
}
starts.sort((a, b) => a[0] - b[0]);
function lowerBound(arr, target) {
let left = 0, right = arr.length;
while (left < right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid][0] < target) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
let ans = new Array(n);
for (let i = 0; i < n; i++) {
let end = intervals[i][1];
let idx = lowerBound(starts, end);
if (idx === starts.length) {
ans[i] = -1;
} else {
ans[i] = starts[idx][1];
}
}
return ans;
}
let intervals = [[3,4],[2,3],[1,2]];
console.log(findRightInterval(intervals));