数组中的二分查找函数: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;
}

运行结果:

相关推荐
wuweijianlove19 小时前
算法性能的渐近与非渐近行为对比的技术4
算法
_dindong19 小时前
cf1091div2 C.Grid Covering(数论)
c++·算法
AI成长日志19 小时前
【Agentic RL】1.1 什么是Agentic RL:从传统RL到智能体学习
人工智能·学习·算法
黎阳之光20 小时前
黎阳之光:视频孪生领跑者,铸就中国数字科技全球竞争力
大数据·人工智能·算法·安全·数字孪生
skywalker_1120 小时前
力扣hot100-3(最长连续序列),4(移动零)
数据结构·算法·leetcode
6Hzlia20 小时前
【Hot 100 刷题计划】 LeetCode 17. 电话号码的字母组合 | C++ 回溯算法经典模板
c++·算法·leetcode
wfbcg20 小时前
每日算法练习:LeetCode 209. 长度最小的子数组 ✅
算法·leetcode·职场和发展
_日拱一卒20 小时前
LeetCode:除了自身以外数组的乘积
数据结构·算法·leetcode
计算机安禾21 小时前
【数据结构与算法】第36篇:排序大总结:稳定性、时间复杂度与适用场景
c语言·数据结构·c++·算法·链表·线性回归·visual studio
SatVision炼金士21 小时前
合成孔径雷达干涉测量(InSAR)沉降监测算法体系
算法