查存在
if (pos.count(need)) {
// need 已经出现过
}count 对 map/unordered_map 都可用,在这里表示 key 是否存在。
两数之和模板
unordered_map<int, int> pos;
for (int i = 0; i < n; i++) {
int need = target - a[i];
if (pos.count(need)) cout << pos[need] << ' ' << i;
pos[a[i]] = i;
}先查 need,再放当前数,可以避免同一个元素被重复使用。
频次统计
unordered_map<string, int> cnt;
for (string word : words) cnt[word]++;看到“出现次数”“分组”“是否存在”,优先想到哈希表。