二分查找,最关键的就是如何确定查找的条件以及左右边界的取值。
一般有两种方法
[left,right] 左闭右闭
且right初始值为nums.length-1
此时的循环条件为while(left<=right),并且在目标值在中间值左边时,调整right=mid-1
var search = function(nums, target) {
let left=0;
let right=nums.length-1;
while(left<=right){
let mid=Math.floor((left+right)/2);
if(target>nums[mid]){
left=mid+1;
}else if(target<nums[mid]){
right=mid-1;
}else{
return mid;
}
}
return -1;
};
[left,right) 左闭右开
right初始值为nums.length
此时的循环条件为while(left<right),并且在目标值在中间值左边时,调整right=mid
var search = function(nums, target) {
let left=0;
let right=nums.length;
while(left<right){
let mid=Math.floor((left+right)/2);
if(target>nums[mid]){
left=mid+1;
}else if(target<nums[mid]){
right=mid;
}else{
return mid;
}
}
return -1;
};