C++的STL进一步总结之lower_bound和upper_bound

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41282486/article/details/80708751

一、lower_bound

用法:int t=lower_bound(a+l,a+r,m)-a
解释:在升序排列的a数组内二分查找[l,r)区间内的值为m的元素。返回m在数组中的下标。
特殊情况:
1.如果m在区间中没有出现过,那么返回第一个比m大的数的下标。
2.如果m比所有区间内的数都大,那么返回r。这个时候会越界,小心。
3.如果区间内有多个相同的m,返回第一个m的下标。
时间复杂度:
一次查询O(log n),n为数组长度。
实际上对长度为1000000的数组来1000000次lower_bound,学校渣电脑1.5-1.6s
自己手写的二分在1.2-1.4s左右
也不是很慢。

然后注意:m可以是pair等等。还有下标从0开始还是从1开始。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[1000010],t,n,l,r;
int main()
{
	//freopen("data.in","r",stdin);
	//freopen("data.out","w",stdout);
	scanf("%d",&t);
	for(int i=0;i<t;++i)
		scanf("%d",&a[i]);
	for(int i=0;i<t;++i)
	{
		scanf("%d%d%d",&l,&r,&n);//在[l,r)区间内查找n
		printf("%d\n",lower_bound(a+l,a+r,n)-a);
	}
}

二、upper_bound
用法:int t=upper_bound(a+l,a+r,m)-a
解释:在升序排列的a数组内二分查找[l,r)区间内的值为m的元素。返回m在数组中的下标+1。
特殊情况:
1.如果m在区间中没有出现过,那么返回第一个比m大的数的下标。
2.如果m比所有区间内的数都大,那么返回r。这个时候会越界,小心。
3.如果区间内有多个相同的m,返回最后一个m的下标+1。
时间复杂度:
一次查询O(log n),n为数组长度。
实际上对长度为1000000的数组来1000000次upper_bound,学校渣电脑1.5-1.6s
自己手写的二分在1.2-1.4s左右
也不是很慢。
然后注意:m可以是pair等等。还有下标从0开始还是从1开始。

下面给出代码


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[1000010],t,n,l,r;
int main()
{
	//freopen("data.in","r",stdin);
	//freopen("data.out","w",stdout);
	scanf("%d",&t);
	for(int i=0;i<t;++i)
		scanf("%d",&a[i]);
	for(int i=0;i<t;++i)
	{
		scanf("%d%d%d",&l,&r,&n);<span style="font-family: Arial, Helvetica, sans-serif;">//在[l,r)区间内查找n</span>
		printf("%d\n",upper_bound(a+l,a+r,n)-a);
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_41282486/article/details/80708751