数组中的二分查找函数:lower_bound【第一个 >= 目标值的元素的值或者下标】 和 upper_bound【第一个 > 目标值的元素的值或者下标】

前提:数组必须是有序的【最好是升序的】

举例:数组:[1, 2, 3, 3, 3, 7,8]查找目标值:3

lower_bound → 指向第一个 3的迭代器,解引用后可得到值

upper_bound → 指向第一个比 3 大的数(7),解引用后可得到值

【在数组中是否可以找到目标值】可执行代码:

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
const int N=1e4+10;
vector<int> a(N);
int main(){
a={1,2,3,3,3,7,8};
int target=5;//将要查找的值设为3. 
vector<int>::iterator ret1=lower_bound(a.begin(),a.begin()+7,target);//返回数组中第一次出现3的位置的下标。
//如果数组中没有找到这个元素,就返回数组中第一次出现大于3的位置的下标
vector<int>::iterator ret2=upper_bound(a.begin(),a.begin()+7,target);//返回数组中第一次出现大于3的位置的下标 
cout<<*ret1<<endl<<*ret2<<endl;
if(target==*ret1) cout<<"在数组中可以找到目标值:"<<target<<endl;
else cout<<"在数组中不可以找到目标值"<<endl;
}

运行结果:

lower_bound -a.begin()→ 指向第一个 3的下标

upper_bound -a.begin()→ 指向第一个比 3 大的数(7)的下标

【得到目标值第一次出现的下标和目标值最后一次出现下标的下一个位置】可执行代码:

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
const int N=1e4+10;
vector<int> a(N);
int main(){
a={1,2,3,3,3,7,8};
int target=3;//将要查找的值设为3. 
int ret1=lower_bound(a.begin(),a.begin()+7,target)-a.begin();//返回数组中第一次出现3的位置的下标。
//如果数组中没有找到这个元素,就返回数组中第一次出现大于3的位置的下标
int ret2=upper_bound(a.begin(),a.begin()+7,target)-a.begin();//返回数组中第一次出现大于3的位置的下标 
cout<<ret1<<endl<<ret2;
}

运行结果:

【修改一下,将目标值改为数组中未出现的元素时lower_bound()和upper_bound()函数值的变化】可执行代码:

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
const int N=1e4+10;
vector<int> a(N);
int main(){
a={1,2,3,3,3,7,8};
int target=5;//将要查找的值设为5. 
int ret1=lower_bound(a.begin(),a.begin()+7,target)-a.begin();//返回数组中第一次出现3的位置的下标。
//如果数组中没有找到这个元素,就返回数组中第一次出现大于5的位置的下标
int ret2=upper_bound(a.begin(),a.begin()+7,target)-a.begin();//返回数组中第一次出现大于5的位置的下标 
cout<<ret1<<endl<<ret2;
}

运行结果:

相关推荐
倒头就睡的小比特5 天前
算法竞赛C++常用的STL
c++·算法
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
猎头南楼5 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
m0_547486665 天前
《数据结构教程》全套 PPT课件2026
数据结构
旖旎夜光5 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark5 天前
大规模并行计算中的负载均衡算法研究4
算法
Because_of_Her15 天前
并查集-听课笔记
笔记·算法·并查集
码流子5 天前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环
大数据·人工智能·物联网·算法·架构
another heaven5 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
wzdark5 天前
从算法设计模式看编程思维的抽象能力4
算法