-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0704_binary_search.js
55 lines (54 loc) · 1.42 KB
/
0704_binary_search.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
/**
* @description Return left border in binary search
* @param {Object []} collection
* @param {Number} target
* @returns {Number}
*/
const leftBorder = (collection, target) => {
let left = -1;
let right = collection.length;
while (right - left > 1) {
const middle = Math.trunc((left + right) / 2);
if (collection[middle] < target) {
left = middle;
} else { // collection[middle] >= target
right = middle;
}
}
return left;
};
/**
* @description Return right border in binary search
* @param {Object []} collection
* @param {Number} target
* @returns {Number}
*/
const rightBorder = (collection, target) => {
let left = -1;
let right = collection.length;
while (right - left > 1) {
const middle = Math.trunc((left + right) / 2);
if (collection[middle] > target) {
right = middle;
} else { // collection[middle] >= target
left = middle;
}
}
return right;
};
/**
* @link https://leetcode.com/problems/binary-search/
* @description write a function to search target in nums.
* If target exists, then return its index. Otherwise, return -1.
* @param {Object []} collection
* @param {Number} target
* @returns
*/
const binarySearch = (collection, target) => {
const leftBoundary = leftBorder(collection, target);
const rightBondary = rightBorder(collection, target);
if (rightBondary - leftBoundary === 1) {
return -1;
}
return leftBoundary + 1;
};