forked from JoshCrozier/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0704-binary-search.js
44 lines (38 loc) · 1.03 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
/**
* 704. Binary Search
* https://leetcode.com/problems/binary-search/
* Difficulty: Easy
*
* Given an array of integers nums which is sorted in ascending order, and an
* integer target, write a function to search target in nums. If target exists,
* then return its index. Otherwise, return -1.
*
* You must write an algorithm with O(log n) runtime complexity.
*/
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
let left = 0;
let right = nums.length - 1;
while (left <= right) {
const pivot = Math.floor((right + left) / 2);
if (nums[pivot] === target) return pivot;
if (target < nums[pivot]) right = pivot - 1;
else left = pivot + 1;
}
return -1;
};
// var search = function(nums, target) {
// l = 0
// r = nums.length
// while (l <= r) {
// pivot = Math.floor((l + r) / 2)
// if (nums[pivot] === target) return pivot
// if (target < nums[pivot]) r = pivot - 1
// else l = pivot + 1
// }
// return - 1
// };