HashMap
HashMap
HashMap in Python - Counter
from collections import Counter
在腾讯面试的过程中,被问到了一个题目,要求找出一个数组中第一个单独出现的数字,例如 [2, 4, 2, 3, 1, 3], 则结果应该是 4.
题目如果用 hashmap 去求解的话只需要:
from collections import Counter
nums = [2, 4, 2, 3, 1, 3]
nums_counter = Counter(nums)
res = min(nums_counter, key = nums_counter.get)
Counter 为 Python 内置的 hashmap, 具体可以查询 Counter, 对于那个排序而言,key 会指定一个函数用于元素的比较,nums_counter.get() 方法用于得到某个 key 的 value 值。
unordered_map
-
What is difference between
mapandunordered_map?
Conclusion: unordered_map is generally use more memory, better for lookup-retrieval, much slower at repeatedly inserting and removing elements.
Code example for map usage: GitHub: 如何遍历、赋值。
关联容器 unordered_map 的初始化:
unordered_map<char, int> roman = {
{'I', 1},
{'V', 5}
};
也可以利用 for 循环赋值初始化,具体参照上述 GitHub 示例。
:::tip 拓展 Python map 的初始化比较简单:
mapping = {
"]":"[",
"}":"{"
}
注意加以区别! :::
map
Example: 单词计数器
Using map’s includes:
#include <map>
#include <string>
using Map = std::map<std::string, std::size_t>;
Map my_map;
auto count()
{
Map counts;
for (string w; cin >> w; ++counts[w])
;
return counts;
}
Print this map’s key and value:
for(auto &kv : my_map)
std::cout << kv.first << : << kv.second << std::endl;
// words : counts 修改历史9 次提交
- refactor: reorganize documentation structure and update Navbar componentxiaocheng··
2fb8f42 - chore(project): clean up obsolete configuration and build artifactsxiaocheng··
3574bd3 - new struct for lblogsxiaocheng··
8c9b28e - move blogs to docsxiaocheng··
c8535a0 - update codechenweigao··
e4c6887 - update fix: timeline errorchenweigao··
fb4b591 - update Datechenweigao··
3c14689 - init v3chenweigao··
b770fc2 - init v2chenweigao··
505f81b