-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.js
More file actions
38 lines (33 loc) · 781 Bytes
/
Copy pathsolution.js
File metadata and controls
38 lines (33 loc) · 781 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
class Solution {
cntInRange(arr, queries) {
// Step 1: Sort the array
arr.sort((a, b) => a - b);
const result = [];
for (let [a, b] of queries) {
let left = this.lowerBound(arr, a);
let right = this.upperBound(arr, b);
result.push(right - left);
}
return result;
}
lowerBound(arr, target) {
let l = 0,
r = arr.length;
while (l < r) {
let mid = Math.floor((l + r) / 2);
if (arr[mid] < target) l = mid + 1;
else r = mid;
}
return l;
}
upperBound(arr, target) {
let l = 0,
r = arr.length;
while (l < r) {
let mid = Math.floor((l + r) / 2);
if (arr[mid] <= target) l = mid + 1;
else r = mid;
}
return l;
}
}