5 April 2024
Easy
704. Binary Search
Link: https://leetcode.com/problems/binary-search
Description: Implement a binary search algorithm to find the target value in a sorted array.
Solution:
Create two pointers, left
and right
, that represent the range of the array to search. While the left
pointer is less than or equal to the right
pointer, calculate the middle index m
. If the value at index m
is equal to the target, return m
. If the value at index m
is greater than the target, update the right
pointer to m - 1
. If the value at index m
is less than the target, update the left
pointer to m + 1
. If the target is not found, return -1
.
/**
* @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 m = left + Math.floor((right - left) / 2)
if (nums[m] === target) {
return m
} else if (nums[m] > target) {
right = m - 1
} else {
left = m + 1
}
}
return -1
}