#include<bits/stdc++.h>
using namespace std;
//查找到第一个大于或等于target的数字 找到返回该数字的地址 不存在则返回end
int Lower_bound(int a[],int Start,int End,int target){
int L = 0;
//数组下标
int R = End - 1;
int fristpop = End;
while(L<=R){
//防止(L+R)/ 2 过大数据溢出
int mid = L + (R - L ) / 2;
if(a[mid] < target){
L = mid + 1;
fristpop = L;
}
else
R = mid - 1;
}
}
//查找到第一个大于target的数字 找到返回该数字的地址 不存在则返回end
int Upper_bound(int a[],int Start,int End,int target){
int L = 0;
int R = End - 1;
int fristabove = End;
while(L<=R){
int mid = L + (R - L) / 2;
if(a[mid] <= target){
//将L记忆化 要找到大于的数字 对立思想 就是在小于等于该目标数值的下标往前挪移为一位就是大于或等于target
L = mid + 1;
fristabove = L;
}
else
R = mid - 1;
}
}
int main()
{
int a[5] = {1,2,3,4,10};
//注意 此时输出得是数组下标 不是数组值
//离5最接近得是4 4得数组下标是3 a[3] = 4 a[4] = 10
printf("%d\n",Lower_bound(a,0,sizeof(a) / sizeof(int),2));
printf("%d",Upper_bound(a,0,sizeof(a) / sizeof(int),5));
return 0;
}
Lower_bound Upper_bound实现c++
最新推荐文章于 2023-12-26 12:05:22 发布