https://leetcode.cn/problems/...

解题思路

  1. 确定左右
  2. 计算中间
  3. 中间大于目标则表示右边只会更大于目标,舍弃
  4. 中间小于目标则表示左边只会更小于目标,舍弃
  5. 修改左或右为中间

image.png

/**
* @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
};

TaoWu
15 声望2 粉丝