不需要考虑mid+1、mid-1的二分查找模板
一种更便于记忆的二分法
- l = -1, r = n;
- l = mid, r = mid;
- while(l + 1 != r);
模板
int L=-1,R=n;
while(L+1!=R)
{
int mid=L+R>>1;
if(check()) L=mid;
else R=mid;
//最后根据你所分左右两边区间的结果
//选取L或者R作为结果
}
AcWing 789. 数的范围
#include<iostream>
using namespace std;
const int N = 1e6 + 10;
int n, q, k, a[N];
int main(){
cin >> n >> q;
for(int i = 0; i < n; i++)scanf("%d", &a[i]);
while(q--){
scanf("%d", &k);
int l = -1, r = n;
while(l + 1 != r){
int mid = l + r >> 1;
if(a[mid] < k) l = mid;
else r = mid;
}
if(a[r] != k){
cout << -1 << " " << -1 << endl;
continue;
}
int ll = -1, rr = n;
while(ll + 1 != rr){
int midd = ll + rr >> 1;
if(a[midd] <= k) ll = midd;
else rr = midd;
}
cout << r << " " << ll << endl;
}
}
https://blog.csdn.net/WJPnb1/article/details/126360962?spm=1001.2014.3001.5502