Leetcode—— Group Anagrams

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;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值