二分查找
以前写的二分查找太依赖STL了,导致遇到一些情况下STL并不好用,比如:
如果数组元素是倒序排列,这时的STL就不好用了;
所以这里总结一下手写二分;
容器元素是递增的,从容器中找第一个大于或等于 查找值 的元素的下标,相当于lower_bound;
#include<bits/stdc++.h>
#define ll long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=100100;
const int M=1000100;
const ll mod=998244353;
int main(){
ios::sync_with_stdio(false);
int a[10];
for(int i=1;i<=9;i++) a[i]=i;//单调递增
int l=1,r=9;
while(l<=r){
int d=(l+r)/2;
if(a[d]>=5) r=d-1;
else l=d+1;
}
cout<<l<<endl;
return 0;
}
容器元素是递增的,从容器中找最后一个小于或等于 查找值 的元素的下标。
这个和上面的是一样求的,>=改为>,最后答案 减1;相当于upper_bound();
容器元素是递减的,从容器中找第一个小于或等于 查找值 的元素的下标;
代码:
#include<bits/stdc++.h>
#define ll long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=100100;
const int M=1000100;
const ll mod=998244353;
int main(){
ios::sync_with_stdio(false);
int a[10];
for(int i=1;i<=9;i++) a[i]=10-i;//单调递增
int l=1,r=9;
while(l<=r){
int d=(l+r)/2;
if(a[d]<=5) r=d-1;
else l=d+1;
}
cout<<l<<endl;
return 0;
}
容器元素是递减的,从容器中找最后一个大于或等于 查找值 的元素的下标;
这个和第3个是一样的,最后答案减1;