答:
这里提供一个不用二分查找的做法,使用C++内置的哈希表(unordered_map):
#include <cstdio>
#include <unordered_map>
using namespace std;
int main()
{
int n;
scanf("%d", &n);
unordered_map<int, int> pos;
for(int i=1; i<=n; i++)
{
int x;
scanf("%d", &x);
pos.emplace(x, i);
}
int q;
scanf("%d", &q);
while(q--)
{
int x;
scanf("%d", &x);
auto it = pos.find(x);
if(it == pos.end())
puts("no");
else printf("%d\n", it->second);
}
return 0;
}
时间复杂度只有 O(n + k),二分查找是 O(n + k log n)。