Skip to content

Latest commit

 

History

History
32 lines (28 loc) · 945 Bytes

Binary Search.md

File metadata and controls

32 lines (28 loc) · 945 Bytes

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.

Screen Shot 2021-11-13 at 13 49 19

Time complexity : O(logN). Space COmplexity: O(N)

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