P2249 【深基13.例1】查找(二分查找)

https://www.luogu.com.cn/problem/P2249
//寻找左侧边界的二分搜索
#include<bits/stdc++.h>
using namespace std;
#define N 1000005
#define ll long long
ll a[N], l, r, mid;
int main(){
	int n, m, key;
	cin >> n >> m;
	for(int i=1; i<=n; i++)
		cin >> a[i];
	while(m--){
		cin >> key;
		l = 1, r = n;
		while(l < r){
			mid = l + ((r-l)>>1);
			if(a[mid] >= key)
				r = mid;
			else if(a[mid] < key)
				l = mid + 1;
		}
		if(a[r] == key)
			cout << r << " ";
		else
			cout << "-1 ";
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39053800/article/details/107098007