二分查找
- 左闭右开
int binarySearch(vector<int> &nums, int target){
int left = 0,right = nums.size(),mid = 0;
while(left < right){
mid = left + (right - left) >> 2;
if(target > nums.at(mid){
left = mid + 1;
}else if(target < nums.at(mid)){
right = mid;
}else{
return mid;
}
}
return left;
}
- 左闭右闭
int binarySearch(vector<int> &nums, int target){
int left = 0, right = nums.size()-1,mid = 0;
while(left <= right){
mid = left + (right - left) >> 2;
if(target > nums.at(mid){
left = mid + 1;
}else if(target < nums.at(mid)){
right = mid - 1;
}else{
return mid;
}
}
return left
}