突发奇想
作为一名蒟蒻,我一开始是用递归写的二分,然后果不其然地TLE了
懒得再写一遍循环的我突然想到有unordered_map这么个东西,理论单次查询的时间为O(1),比二分的O(log n)还快。于是就有了这么个东西:
#include<iostream>
#include<unordered_map>
using namespace std;
long long read() {
long long a = 0;
char c = getchar();
while (c < '0' || c > '9') c = getchar();
while (c >= '0' && c <= '9') {
a = a * 10 + (c - '0');
c = getchar();
}
return a;
}
int main() {
long long temp=0, q=0, n, m;
cin >> n >> m;
unordered_map<long long, int> a;
for (int i = 0; i < n; i++){
temp=read();
if(a[temp]==0) a[temp]=i+1;
}
for (int i = 0; i < m; i++) {
q=read();
cout << (a[q]==0?-1:a[q]) << ' ';
}
return 0;
}
结果很轻松地过了,不比二分慢多少
疑问
可是按理说对于静态有序的数据二分查找会更快,所以到底哪种解法更优呢?