C++ lower_bound 与 upper_bound函数

头文件:#include <algorithm>

时间复杂度:一次查询O(log n),n为数组长度。

图示:

lower_bound:

功能:查找非递减序列[first,last) 内第一个大于或等于某个元素的位置。

返回值:如果找到返回找到元素的地址否则返回last的地址。(这样不注意的话会越界,小心)

用法:int t=lower_bound(a+l,a+r,key)-a;(a是数组)。

upper_bound:

功能:查找非递减序列[first,last) 内第一个大于某个元素的位置。

返回值:如果找到返回找到元素的地址否则返回last的地址。(同样这样不注意的话会越界,小心)

用法:int t=upper_bound(a+l,a+r,key)-a;(a是数组)。

注意 调用之前必须确定序列为有序序列,否则调用出错。

相关题目 UVA - 10474

AC代码

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=10000;
int main()
{
    int a,b,s[maxn],key;
    key=0;
    while(scanf("%d%d",&a,&b)==2&&a){
    printf("CASE# %d:\n",++key);
    for(int i=0;i<a;i++)
       scanf("%d",&s[i]);
        sort(s,s+a);
    while(b--){
        int m;
        cin>>m;
        int p=lower_bound(s,s+a,m)-s;
        if(s[p]==m)
            printf("%d found at %d\n",m,p+1);
        else
            printf("%d not found\n",m);
    }
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值