二分法查找一个数
int my_binary_search_one_number(vector<int> nums, int target) //查找某个数的位置
{
int left=0;
int right=nums.size()-1;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]<target){
left=mid+1;
}
else if(nums[mid]>target){
right=mid-1;
}
else if(nums[mid]==target){
return mid; //找到 返回mid位置
}
}
return -1; //没有找到 返回-1
}
二分法查找一个数在数组中的左边界
int my_binary_search_left_of_one_number(vector<int> nums, int target)
{
int left=0;
int right=nums.size()-1;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]<target){
left=mid+1;
}
else if(nums[mid]>target){
right=mid-1;
}
//继续找左边界
else if(nums[mid]==target){
right=mid-1;
}
}
//检查left是否越界
if(left>=nums.size()||nums[left]!=target){
return -1;
}
return left;
}
二分法查找一个数在数组中的左边界
int my_binary_search_right_of_one_number(vector<int> nums, int target)
{
int left=0;
int right=nums.size()-1;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]<target){
left=mid+1;
}
else if(nums[mid]>target){
right=mid-1;
}
//继续找右边界
else if(nums[mid]==target){
left=mid+1;
}
}
//检查right是否越界
if(right<0||nums[right]!=target){
return -1;
}
return right;
}
int main()
{
vector<int>nums={1,2 ,3, 4, 5 ,6, 7,7,7,7,7,7,7,7,7,7,90 ,111, 121 ,121,123, 1231};
int target=7;
int ans=-2;
int ansl=-2;
int ansr=-2;
ans=my_binary_search_one_number(nums,target);
ansl=my_binary_search_left_of_one_number(nums,target);
ansr=my_binary_search_right_of_one_number(nums,target);
cout<<endl<<ans<<endl<<ansl<<endl<<ansr<<endl;
return 0;
}
感谢labuladong的知识分享,原文地址我作了首诗,保你闭着眼睛也能写对二分查找