分析
是一个比较简单的哈希表的题目,可是拿到这个题我想到了用映射表map,鉴于需要保留输入时的顺序,我以为unordered_map会按照输入顺序存放,于是使用了unordered_map。
#include<iostream>
#include<unordered_map>
using namespace std;
unordered_map<int, int> m;
int main() {
int n; cin >> n;
while (n--) {
int t; cin >> t;
m[t]++;
}
for (auto it : m) {
if (it.second == 1) {
cout << it.first<<endl;
return 0;
}
}
cout << "None"<<endl;
return 0;
}
发现无法AC。于是去查官方文档:
unordered_map中的元素相对于其键或映射不按任何特定顺序排序值,但根据其哈希值将其组织为存储桶,以允许直接通过其键值快速访问各个元素
因此,unordered_map并不是按照输入顺序存放,而是按照内部的哈希函数组织成的“存储桶”存放,即它是一个未知的顺序。
改用普通的hash数组
#include<iostream>
using namespace std;
int m[10001], a[100000];
int main() {
int n; cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
m[a[i]]++;
}
for (int i = 0; i < n; i++) {
if (m[a[i]] == 1) {
cout << a[i];
return 0;
}
}
cout << "None";
return 0;
}