二分查找:在升序数组nums中寻找目标值target,对于特定下标ii,比较nums[i]和target的大小:
主要注意两点:
(1)middle=Math.floor((right - left) / 2) + left;
(2)因为不用和middle比较所以要+1或-1
nums[i] > targt时,在i左侧,所以要改变右侧right=middle-1
nums[i] < targt时,在i右侧,所以要改变左侧left=middle+1
练习地址:https://leetcode-cn.com/problems/binary-search/
/** * @param {number[]} nums * @param {number} target * @return {number} */ var search = function(nums, target) { let len = nums.length; let left = 0, right = len - 1; while(left <= right) { let middle = Math.floor((right - left) / 2) + left; if(nums[middle] > target) { right = middle - 1; } else if (nums[middle] < target) { left = middle + 1; } else if (nums[middle] === target) { return middle; } } return -1; };