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

运行结果:

相关推荐
饮水桶_T12 小时前
C++ STL00 | 六大核心组件协作框架 笔记
开发语言·算法·百度·facebook·新浪微博
大今野14 小时前
第 13 章 数据结构:二叉树遍历、栈与队列、图与排序全考点(专转本计算机必考)
数据结构·专转本
饮水桶_T14 小时前
Java调用大语言模型、多轮对话 笔记
笔记·算法·设计模式·电脑·ai编程
AAA修煤气灶刘哥15 小时前
QQ 音乐怎么在 25 毫秒内,决定一句话该交给谁?
人工智能·算法·llm
开开心心就好16 小时前
电脑禁止自动休眠工具,还能按负载定时
算法·智能手机·pdf·电脑·word·音视频·lua
拾码录17 小时前
深入理解链表:动态数据结构的基石
c语言·数据结构·链表
geovindu1 天前
python:DecisionTree
开发语言·后端·python·算法
geovindu1 天前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
AllData公司负责人1 天前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris