当前位置:网站首页>lower_bound,upper_bound,二分
lower_bound,upper_bound,二分
2022-06-11 04:34:00 【superkcl2022】
#include <iostream>
using namespace std;
/** * lower_bound 若有多個等於target的數,返回最左邊的那個數,否則返回 > target的那個數的下標 * 如果 tar最小返回0,如果tar最大返回數組最大值下標+1 * * * 1. target的值比cnt[0]小,while循環直到 l == r == 0, a[0] >= tar 返回0 * 2. target最大, 會一直執行這條語句 a[mid] < tar ,index的值不變 * */
/** * 二分,log級別,未查詢到葉子節點,即可停止,而lower_bound停不下來,一直到葉子節點 * */
int lower_bound(int a[],int l,int r,int tar){
int index = r+1;
while(l <= r){
int mid = l + (r-l)/2;
if(tar > a[mid]) l = mid + 1; //中間值小了
else {
// a[mid] == tar時,r = mid - 1
index = mid;
r = mid - 1;
}
}
return index;
}
int upper_bound(int a[],int l,int r,int tar){
int index = r+1;
while(l <= r){
int mid = l + (r-l)/2;
if(tar >= a[mid]) l = mid + 1;
else{
index = mid;
r = mid - 1;
}
}
return index;
}
int main() {
int cnt[] = {
2,4,4,5,7,8,9};
cout << lower_bound(cnt,0,sizeof(cnt)/sizeof(int)-1,14) << endl;
cout << upper_bound(cnt,0,sizeof(cnt)/sizeof(int)-1,4) << endl;
return 0;
}
边栏推荐
- Collation of construction data of Meizhou plant tissue culture laboratory
- JVM (2): loading process of memory structure and classes
- 正大国际;做主帐户需要了解什么
- 国际期货黄金手续费怎么算?
- Unity map mapping
- Feature selection algorithm based on bare bones particleswarm optimization
- 谷歌的代码覆盖率最佳实践
- Overview of construction knowledge of Fuzhou mask clean workshop
- Vulkan official example interpretation raytracing
- MySQL锁总结
猜你喜欢

PostgreSQL database replication - background first-class citizen process walreceiver receiving and sending logic

MySQL锁总结

How the idea gradle project imports local jar packages

Emlog新版导航源码/带用户中心

JVM(6):Slot变量槽、操作数栈、代码追踪、栈顶缓存技术

项目架构演进

强大新UI装逼神器微信小程序源码+多模板支持多种流量主模式

PostgreSQL数据库复制——后台一等公民进程WalReceiver 收发逻辑

MySQL stored procedure

新UI学法减分专业版34235道题库学法减分专业版小程序源码
随机推荐
Exness: Liquidity Series - order Block, Unbalanced (II)
mysql存储过程
Guanghetong launched a new generation of 3GPP R16 industrial 5g module fg160 engineering sample
Unity 传送机制的实现
Acts: how to hide defects?
Carbon path first, Huawei digital energy injects new momentum into the green development of Guangxi
Exness: liquidity series - order block, imbalance (II)
Record an ES accident
codesys 获取系统时间
Unity 在不平坦的地形上创建河流
Unity Editor Extension save location
The third small class discussion on the fundamentals of information and communication
智慧工地怎样做到数字化转型?
How can smart construction sites achieve digital transformation?
[laser principle and application-2]: key domestic laser brands
JVM(3):类加载器分类、双亲委派机制
关于串口波特率的的记录
碳路先行,华为数字能源为广西绿色发展注入新动能
JVM (7): dynamic link, method call, four method call instructions, distinguishing between non virtual methods and virtual methods, and the use of invokedynamic instructions
SQL optimization