leetcode/notes/src/hash_table.md

57 lines
1.6 KiB
Markdown
Raw Normal View History

2022-12-03 02:38:05 +00:00
# 总结
当我们需要判断某个元素是否出现过时,考虑用哈希表。
## unordered_map 与 unordered_set
这俩的底层都是用哈希函数实现的,因此访问其中的元素可以达到 O(1) 的时间复杂度。
它们的区别在于unordered_map 存储的是 key-value ,而 unordered_set 只存储 key 。
一般我们直接用 unordered_map 就可以完成所有操作了。
常见用法:
```cpp
#include <iostream>
#include <string>
#include <unordered_map>
int main(int argc, const char *argv[]) {
// key 为 std::string 类型的value 为 int 类型的
std::unordered_map<std::string, int> map;
// 插入
map["foo"] = 1;
map["bar"] = 2;
map["non"] = 3;
// 访问
std::cout << map["foo"] << std::endl;
// 删除
map.erase("foo");
// 判断元素是否存在
if (map.count("bar") > 0) {
std::cout << "Exist" << std::endl;
} else {
std::cout << "Not exist" << std::endl;
}
// 另一种判断元素是否存在的方法
// find() 会返回元素的正向迭代器,如果没找到则返回 end()
if (map.find("bar") != map.end()) {
std::cout << "Exist" << std::endl;
} else {
std::cout << "Not exist" << std::endl;
}
// 合并两个 unordered_map
std::unordered_map<std::string, int> newMap;
newMap["microsoft"] = 1;
newMap["surface"] = 1;
map.insert(newMap.begin(), newMap.end());
// 遍历
for (std::unordered_map<std::string, int>::iterator iter = map.begin();
iter != map.end(); ++iter) {
std::cout << iter->first << iter->second << std::endl;
}
return 0;
}
```