重点区分:
while(left < right)
和 while(left <= right)
right = middle和
right = middle - 1
当处于左闭右闭区间内时,while(left <= right)
当处于左闭右开区间时,while(left < right)
right = middle和
right = middle - 1,以此类推
1.原理(来源代码随想录)
(1)第一种情况
(2)第二种情况
2.代码(java版)
class Solution {
public int search(int[] nums, int target) {
if (target < nums[0] || target > nums[nums.length - 1]) {
return -1;
}
int left=0;
int right=nums.length-1;
while(left<=right){
int middle=(left+right)/2;
if (nums[middle]>target){
right=middle-1;
}else if (nums[middle]<target){
left=middle+1;
}else {
return middle;
}
}
return -1;
}
}