乐趣区

关于javascript:算法leetcode-704-二分查找

https://leetcode.cn/problems/…

解题思路

  1. 确定左右
  2. 计算两头
  3. 两头大于指标则示意左边只会更大于指标,舍弃
  4. 两头小于指标则示意右边只会更小于指标,舍弃
  5. 批改左或右为两头

/**
* @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
};
退出移动版