Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7839ca2

Browse files
committed
Added 704. Binary Search
1 parent f4597c2 commit 7839ca2

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

javascript/704-Binary-Search.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number}
5+
*/
6+
var search = function (nums, target) {
7+
8+
let left = 0;
9+
let right = nums.length - 1;
10+
11+
while (left <= right) {
12+
let middle = Math.floor((left + right) / 2);
13+
14+
if (nums[middle] === target) {
15+
return middle;
16+
} else if (nums[middle] < target) {
17+
left = middle + 1;
18+
} else {
19+
right = middle - 1;
20+
}
21+
}
22+
23+
return -1;
24+
};
25+
26+
// Runtime: 98 ms, faster than 34.02% of JavaScript online submissions for Binary Search.
27+
// Memory Usage: 44.3 MB, less than 99.18% of JavaScript online submissions for Binary Search.

0 commit comments

Comments
 (0)