- 基本用法
- 一道例题
//初始化 unordered_map一道例题umap = { {2, 10},{1, 20},{3,30} }; //遍历unordered_map //注意一个用指针一个用点 for (auto &item : umap) { cout << item.first << " -> " << item.second << endl; } for(auto it = umap.begin();it != umap.end();++it) { cout< first<<" "< second< (4,9)); //数组的形式,如果存在就修改,否则插入 umap[3] = 7; umap[5]=99; //按key删除元素 umap.erase(0); //按迭代器删除元素 umap.erase(umap.begin()); //按key查找元素 auto it = umap.find(3); if(it != umap.end()){ //查找成功,修改其值 it->second=50; } else{ //查找失败,直接插入 umap[3]=88; }
leetcode: 49. 字母异位词分组
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。
示例 1:
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
思路:
开一个哈希表unordered_map
遍历strs,如果排好序的strs[i]在umap的键中,则将未排好序的strs[i],添加到该键对应的vector数组中;如果不在umap的键中,则加入即可。
class Solution {
public:
vector> groupAnagrams(vector& strs) {
vector> res; //保存最后结果
unordered_map> umap;
for(int i=0;i
string temp=strs[i];
sort(temp.begin(),temp.end());
auto it = umap.find(temp);
if(it != umap.end())
it->second.push_back(strs[i]);
else{
vector temp1;
temp1.push_back(strs[i]);
umap[temp]=temp1;
}
}
for (auto &item : umap) {
res.push_back(item.second);
}
return res;
}
};



