确定区间
左闭右闭
left = 0;
right = nums.size() - 1;
while(left <= right){ // 区间为空 结束循环 : (l > r)
//左右相等是合法区间,比如【1,1】只有 元素1
mid = left + (right-left)>>2;
if(nums[mid]>target){
right = mid -1;//为了不包含原来的nums[mid],所以减一
}else if(nums[mid]<target){
left = mid +1;
}else return mid;
}
return -1;
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length-1;
while(left <= right){
int mid =left + (right-left) /2;
if(nums[mid] > target){
right=mid-1;
}else if(nums[mid] < target){
left = mid +1;
}else{
return mid;
}
}
return -1;
}
}
左闭右开
//左闭右开不是合法区间,比如【1,1)没有 元素1
left = 0;
right = nums.size() ;//左闭右开,本来就不包含
while(left < right){ // 区间为空 结束循环 : (l == r)
mid = left + (right-left)/2;
if(nums[mid]>target){
// nums[mid] >= target 查询[l,mid)
right = mid;//左闭右开,本来就不包含
}else if(nums[mid]<target){
// 查询[mid+1,r),
left = mid +1;
}else{
return mid;
}
}
return -1;