(Js) Leetcode 704. Binary search

topic:

Given an n-element ordered (ascending) integer array nums and a target value target, write a function to search for the target in nums and return the subscript if the target value exists, otherwise return -1.
Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 appears in nums and the subscript is 4
Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so it returns -1

prompt:

You can assume that all elements in nums are not repeated.
n will be between [1, 10000].
Each element of nums will be between [-9999, 9999].

Ideas:

Binary search

Wherein  left + (right - left) / 2 on and  (left + right) / 2 the same result, but effectively prevented  left , and  right too much adding directly cause an overflow.

Code:

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

operation result:

 

Guess you like

Origin blog.csdn.net/M_Eve/article/details/113139593