https://leetcode.cn/problems/…
解题思路
- 确定左右
- 计算两头
- 两头大于指标则示意左边只会更大于指标,舍弃
- 两头小于指标则示意右边只会更小于指标,舍弃
- 批改左或右为两头
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {if(nums === null || nums.length === 0) {return -1}
let left = 0
let right = nums.length - 1
while(left <= right) {let mid = left + Math.floor((right - left) / 2)
if(nums[mid] === target) {return mid}
else if(nums[mid] > target) {right = mid - 1}
else if(nums[mid] < target) {left = mid + 1}
}
return -1
};