lower_bound()是返回第一个大于等于 i 值的元素的地址
upper_bound()是返回第一个大于 i 值的元素的地址
lower_bound()是返回第一个小于等于 i 值的元素的地址
upper_bound()是返回第一个小于 i 值的元素的地址
#include
int upper_bound(int l,int r,int x)
{ while(l<r){
int mid=(l+r)/2;
if(a[mid]>x)r=mid;
else l=mid+1;
}
return l;
}
int lower_bound(int l,int r,int x)
{ while(l<r){
int mid=(l+r)/2;
if(a[mid]>=x)r=mid;
else l=mid+1;
}
return l;
}
对比二分查找
int binarysearch(int l,int r,int x)
{ while(l<=r){
int mid=(l+r)/2;
if(a[mid]==x)return mid;
else if(a[mid]>x)r=mid-1;
else l=mid+1;
}
return -1;
}
对比开方
double sqrt(double x)
{ double l=1,r=x,mid;
while(r-l>eps){ //精度 相当于 r>l
mid=(l+r)/2;
if(mid*mid>x)r=mid;
else l=mid;
}
return mid;
}
vector和数组都适用
(~ ̄▽ ̄)~
#include
#include
#include
#include
using namespace std;
bool cmp(int a, int b)
{
return a>b;
}
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(19);
v.push_back(2);
v.push_back(4);
v.push_back(7);
sort(v.begin(),v.end());
for(auto it:v)
{
cout<<it<<' ';
}
printf("\n");
vector<int>::iterator it;
it = lower_bound(v.begin(),v.end(),4);
cout<<"lower bound: "<<*it<<endl;
cout<<"lower bound position: "<<lower_bound(v.begin(),v.end(),4)-v.begin() + 1<<endl;
it = upper_bound(v.begin(),v.end(),4);
cout<<"upper bound: "<<*it<<endl;
cout<<"upper bound position: "<<upper_bound(v.begin(),v.end(),4)-v.begin() + 1<<endl;
cout<<"——逆序——"<<endl;
sort(v.begin(),v.end(), cmp);
for(auto it:v)
{
cout<<it<<' ';
}
printf("\n");
it = lower_bound(v.begin(),v.end(),4, cmp);
cout<<"lower bound: "<<*it<<endl;
cout<<"lower bound position: "<<lower_bound(v.begin(),v.end(),4, cmp)-v.begin() + 1<<endl;
it = upper_bound(v.begin(),v.end(),4, cmp);
cout<<"upper bound: "<<*it<<endl;
cout<<"upper bound position: "<<upper_bound(v.begin(),v.end(),4, cmp)-v.begin() + 1<<endl;
return 0;
}