一个简单的二分查找题。CPP代码。二分查找需要注意的地方就是区间的问题。如果是while(left<right)。就代表着区间定义是[left,right),即右边界取不到。因此当right缩小至middle时候只需要:
while(left<right){
...
if(nums[middle]<target)right=middle;
...
}
如果是两边并区间。则middle不满足条件时候,right不能缩减至middle
while(left<=right)
{
if(nums[middle]<target)right=middle-1;
}
完整代码:
int search(vector<int>&nums,int target)
{
int l=0;
int r=nums.size();
while (l<r)
{
int middle=(l+r)/2;
if (nums[middle]==target)return middle;
if (nums[middle]<target)
{
l=middle+1;
}
else if(nums[middle]>target)
{
r=middle;
}
}
return -1;
}
标签:int,代码,随想录,middle,while,left
From: https://www.cnblogs.com/jiyuebo/p/18462882