P2249 【深基13.例1】查找

题目链接:https://www.luogu.com.cn/problem/P2249
题解代码:

#include<iostream>
using namespace std;

int n, m, q, a[1000005];
int find(int x);
int main()
{
	cin >> n >> m;

	for (int i = 1; i <= n; i++)
		cin >> a[i];

	for (int i = 1; i <= m; i++)
	{
		cin >> q;
		int ans = find(q);
		cout << ans << " ";
	}

	return 0;
}
int find(int x)
{
	int l = 0, r = n+1;
	while (l + 1 != r)
	{
		int mid = (l + r) >> 1;
		if (a[mid] >= x) r = mid;
		else l = mid;
	}
	if (a[l+1] == x) return l+1;
	else return -1;
}
posted @ 2024-11-15 02:45  fufuaifufu  阅读(7)  评论(0编辑  收藏  举报