基本二分查找,找到目标值
int binary_search(vector<int>&nums,int target){
int left =0;
int right = nums.size()-1;
while(left<=right){
int mid = (right-left)/2+left;
if(nums[mid]==target){
return mid;
}
else if(nums[mid]<target){
left = mid+1;
}
else if(nums[mid]>target){
right=mid-1;
}
}
return -1;
}
二分查找,找左边界值
int left_search(vector<int>&nums,int target){
int left= 0;
int right= nums.size()-1;
while(left<=right){
int mid = (right-left)/2+left;
if(nums[mid]==target){
if(mid==0 || nums[mid-1]<target){
return mid;
}
right= mid-1;
}
else if(nums[mid]>target){
right = mid-1;
}
else if (nums[mid]<target){
left= mid+1;
}
}
return -1;
}
二分查找,找右边界值
int right_search(vector<int>&nums,int target){
int left= 0;
int right= nums.size()-1;
while(left<=right){
int mid =(right-left)/2+left;
if(nums[mid]==target){
if(mid==nums.size()-1||nums[mid+1]>target){
return mid;
}
left= mid+1;
}
else if (nums[mid]>target){
right= mid-1;
}
else{
left= mid+1;
}
}
return -1;
}
二分查找模版
最新推荐文章于 2024-09-02 16:35:28 发布