Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
这一题目需要用到散列表:unordered_map
说到散列表,先说一下map,map是通过键-值对来进行存储的,可以通过键查找对应的值,虽然用过查找键返回相应的迭代器,通常情况下,不通过迭代器对其值进行修改。但是可以修改。
map的查找速度相比于vector和list高,但是查找的速度会随着元素的增加而降低。map的底层实现为红黑树,其复杂度为对数。
而unordered_map将键值存储在桶中,插入和查找元素的时间几乎是固定的,而不受容大小的影响。
也用到sort关于sort底层用到那些排序算法,请参考博客:https://blog.csdn.net/qq_33713592/article/details/99674305
代码
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string,vector<string>>m;
vector<vector<string>>res;
for(int i=0;i<strs.size();i++)
{
string s =strs[i];
sort(s.begin(),s.end());
m[s].push_back(strs[i]);
}
for (auto a=m.begin();a!=m.end();a++)
res.push_back(a->second);
return res;
}
};