-
二分搜索方面,STL在库中提供了binary_search,lower_bound,upper_bound.
-
lower_bound是一种应用于有序数据范围内的算法,他可以返回一个迭代器,这个迭代器指向第一个不小于指定值value的元素。
-
通过它,我们可以找出第一个能够恰当插入value的位置,又能维持指定范围内的元素顺序(有序状态)。
-
相对的upper_bound返回的迭代器指向第一个大于指定值value的元素
-
拿酒来一波
#include <iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
int main()
{
int a[14]= {1,1,2,2,2,4,5,5,6,8,8,8,10,15};
int *pos;
int idx;
pos=lower_bound(a,a+14,3);
idx=distance(a,pos);
printf("a[%d] = %d\n",idx,*pos);///a[5]=4
pos=lower_bound(a,a+14,2);
idx=distance(a,pos);
printf("a[%d] = %d\n",idx,*pos);///a[2]=2
return 0;
}
- 分析一下上面代码:
- lower_bound()的前面两个参数用来指定作为对象的数组或容器的范围,比如lower_bound(a,a+14,3),
- 他指定数组a的头指针以及距离头指针14的位置,既数组的末尾。
- 如果a是vector,则可以使用a,begin()和a.end()来指定范围。
- lower_bound()的第三个参数用于指定value。上面的value为3,而数组中第一个不小于3的元素为a[5]=4
- 所以程序将指向a[5]的指针赋值给了*pos
- distance函数用于返回两个指针间的距离,
- 比如:distance(a,pos)会返回a的开头到pos的距离=5
- 那就再上一波
- 滴答滴答---题目链接
-
#include <iostream> #include<string.h> #include<stdio.h> #include<algorithm> using namespace std; const int maxn=1e5+10; int main() { int n; int a[maxn]; scanf("%d",&n); for(int i=0; i<n; i++) { scanf("%d",&a[i]); } int sum=0; int m; scanf("%d",&m); for(int i=0; i<m; i++) { int x; scanf("%d",&x); if(*(lower_bound(a,a+n,x))==x) { sum++; } } printf("%d\n",sum); return 0; }