P2249【深基13.例1】查找
题意:
输入 n 个不超过 10^9的单调不减的非负整数和查找次数m,再输入m个数表示要查找的数的编号。
思路:
给定我们的数据范围太大,直接用暴力枚举的话肯定会超时,这里我们使用二分查找。
数据范围( 1≤n≤10^6, 1≤m≤10^5)
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int a[N];
int main()
{
int n, m;
int x; //需要查找的数的编号
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
}
while (m--)
{
cin >> x;
int l = 1, r = n;
while (l < r)
{
int mid = (l + r) / 2; //取中间点
if (a[mid] >= x)
{
r = mid;
}
else
{
l = mid + 1;
}
}
if (a[l] == x)
{
cout << l << ' ';
}
else
{
cout << -1 << ' ';
}
}
return 0;
}