lower_bound( ) & upper_bound( )
1.对于一个从小到大排序的数组
lower_bound(begin,end,x)
upper_bound(begin,end,x)
前者查找成功返回的是从地址begin到end-1中第一个大于或者等于x的地址,后者查找成功返回的是从地址begin到end-1中第一个大于x的地址,减去begin恰好为数组下标。
2.对于一个从大到小排序的数组
lower_bound(begin,end,x,greater< int >())
upper_bound(begin,end,x,greater< int >())
前者查找成功返回的是从地址begin到end-1中第一个小于或者等于x的地址,后者查找成功返回的是从地址begin到end-1中第一个小于x的地址,减去begin恰好为数组下标。
3.代码实现(帮助理解)
#include <bits/stdc++.h>
using namespace std;
int main()
{
int ans = 0;
int a[5] = {0,1,1,2,3};
ans = lower_bound(a,a+5,1) - a;
cout << ans << endl;//1
ans = upper_bound(a,a+5,1) - a;
cout << ans << endl;//3
ans = lower_bound(a,a+5,4) - a;
cout << ans << endl;//5
ans = upper_bound(a,a+5,4) - a;
cout << ans << endl;//5
vector <int> v = {0,1,1,2,3};
ans = lower_bound(v.begin(),v.end(),1) - v.begin();
cout << ans << endl;//1
ans = upper_bound(v.begin(),v.end(),1) - v.begin();
cout << ans << endl;//3
ans = lower_bound(v.begin(),v.end(),4) - v.begin();
cout << ans << endl;//5
ans = upper_bound(v.begin(),v.end(),4) - v.begin();
cout << ans << endl;//5
//a[5] = {3,2,1,1,0}
sort(a,a+5,greater<int>());
ans = lower_bound(a,a+5,1,greater<int>()) - a;
cout << ans << endl;//2
ans = upper_bound(a,a+5,1,greater<int>()) - a;
cout << ans << endl;//4
ans = lower_bound(a,a+5,4,greater<int>()) - a;
cout << ans << endl;//0
return 0;
}
如果你觉得你又行了,请用lower_bound( ) or upper_bound( )做一下这道题
代码展示
#include <bits/stdc++.h>
using namespace std;
int n,m,k;
int ans;
int a[200010];
int main()
{
cin >> n >> m;
for(int i = 1;i <= n;i++)
{
cin >> a[i];
}
while(m--)
{
int x;
cin >> x;
int sum = upper_bound(a+1,a+n+1,x - 1) - a;
if(a[sum] == x)
{
cout << sum - 1 << " " << upper_bound(a+1,a+n+1,x) - a - 2 << "\n";
}
else
{
cout << -1 << " " << -1 << "\n";
}
}
return 0;
}
. . . . . .