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

50次阅读

共计 436 个字符,预计需要花费 2 分钟才能阅读完成。

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
};

正文完
 0