算法:简单类-二分查找
程序员文章站
2022-03-01 14:53:44
...
https://leetcode-cn.com/problems/binary-search/https://leetcode-cn.com/problems/binary-search/题目
示例 1:
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
示例 2:
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
let left=0,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 {
left = mid + 1;
}
}
return -1;
};