二分模板:
非递归:
int l=0;
int h=n;
while(l<=h)
{
int mid=(l+h)/2;
if(v==a[mid])
{
return mid+1;
}
else if(v>a[mid])
{
l=mid+1;
}
else
{
h=mid-1;
}
}
递归:
int binsearch(int l,int h,int a[], int key)
{
int mid=(l+h)/2;
if(key==a[mid])
{
return mid+1;
}
else if(key>a[mid])
{
l=mid+1;
binsearch(l,h,a,key);
}
else
{
h=mid-1;
binsearch(l,h,a,key);
}
}
}
应用:牛客-二分查找
AC代码:
int upper_bound_(int n, int v, vector<int>& a) {
if(a[n-1]<v)
return n+1;
int l=0;
int h=n;
while(l<=h)
{
int mid=(l+h)/2;
if(v<=a[mid]&&v>a[mid-1])
{
return mid+1;
}
else if(v>a[mid])
{
l=mid+1;
}
else
{
h=mid-1;
}
}
}