例如我们就去找 6 在不在数组中
蓝色框为 l, 红色框为 r ,二分找区间
本题代码:
#include <bits/stdc++.h>
#define endl '\n'
#define int long long
#define INF 0x3f3f3f3f3f
const int N = 1000010;
using namespace std;
int arr[N];
int n,m;
int b_search(int arr[],int n,int x){
int l = -1;
int r = n;
while(l+1<r){
int mid = (l+r)/2;
if(arr[mid]<x){
l = mid;
}else{
r = mid;
}
}
if(arr[r] == x){
return r+1;
}else{
return -1;
}
}
//二分
signed main()
{
std::ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n>>m;
for(int i = 0; i< n; i++){
cin>>arr[i];
}
while(m--){
int x;
cin>>x;
int ans = b_search(arr,n,x);
cout<<ans<<' ';
}
return 0;
}
延申:各种二分查找
up主五点七边的视频 :( BV1d54y1q7k7 )