-
Notifications
You must be signed in to change notification settings - Fork 0
/
everythingBinarySearch.js
59 lines (57 loc) · 1.48 KB
/
everythingBinarySearch.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
function lowerBound(arr, key) {
let ans = -1;
let low = 0;
let high = arr.length - 1;
while (low <= high) {
let mid = low + Math.floor((high - low) / 2);
if (arr[mid] >= key) {
ans = mid;
high = mid - 1;
} else low = mid + 1;
}
return ans;
}
function upperBound(arr, key) {
let ans = -1;
let low = 0;
let high = arr.length - 1;
while (low <= high) {
let mid = low + Math.floor((high - low) / 2);
if (arr[mid] <= key) {
ans = mid;
low = mid + 1;
} else high = mid - 1;
}
return ans;
}
function runProgram(input) {
let newInput = input.split("\n");
let arr = newInput[1].trim().split(" ").map(Number);
let key = Number(newInput[2]);
let lb = lowerBound(arr, key);
let ub = upperBound(arr, key);
if (lb == -1) console.log("-1 -1 0");
else console.log(lb + " " + ub + " " + (ub - lb + 1));
}
if (process.env.USERNAME === "Ajit") {
runProgram(`6
1 1 1 2 2 2
1`);
} else {
process.stdin.resume();
process.stdin.setEncoding("ascii");
let read = "";
process.stdin.on("data", function (input) {
read += input;
});
process.stdin.on("end", function () {
read = read.replace(/\n$/, "");
read = read.replace(/\n$/, "");
runProgram(read);
});
process.on("SIGINT", function () {
read = read.replace(/\n$/, "");
runProgram(read);
process.exit(0);
});
}