Anjan Dutta

Leet Code 704: Binary Search

Leet Code 704: Binary Search

Problem statement:

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.

Constraints:

  • 1 <= nums.length <= 104
  • -104 < nums[i], target < 104
  • All the integers in nums are unique.
  • nums is sorted in ascending order.

Solution:

/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
const len = nums.length;
let start = 0;
let end = len -1;
while (start <= end) {
let mid = parseInt((start+end)/2);
if(nums[mid]===target) {
return mid;
} else if(target < nums[mid]) {
end = mid -1;
} else {
start = mid+1;
}
}
return -1;
};