题解 | 二分查找-I
二分查找-I
https://www.nowcoder.com/practice/d3df40bd23594118b57554129cadf47b
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * [-1,0,3,4,6,10,13,14],13 => 6 * [],3 => -1 * * @param nums int整型一维数组 * @param target int整型 * @return int整型 */ function search(nums, target) { // write code here let left = 0; let right = nums.length - 1; while (left <= right) { console.log(left, right, nums[left]); let middle = Math.floor((right + left) / 2); let val = nums[middle]; if (val === target) return middle; else if (target > val) { left = middle + 1; } else { right = middle - 1; } } return -1; } module.exports = { search: search, };