哈希表专题

1. 两数之和

分析:

1.根据题意,首先需要将要数据选择一个合适的 数据结构模型。  因为是对应相关联,所以我们选择unordered_map

2.因为是一组数,所以用数组 ,将数值与数组下标对应起来

3.已知两数之和,从数组第一个数开始比较,确认余数是否在unordered_map中,如果存在,则使用key值取出其value;如果不在,则以key - value的形式将当前值和当前下表存入unordered_map,然后继续重复执行。

4.将要两个下标传入vector即可

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        unordered_map<int,int> hash;
        for (int i = 0; i < nums.size(); i ++ )
        {
            int another = target - nums[i];
            if (hash.count(another))
            {
                res = vector<int>({hash[another], i});
                break;
            }
            hash[nums[i]] = i;
        }
        return res;
    }
    
};

 

49. 字母异位词分组

分析:题意为把可以组成相同的字符串合并为一组

1.字符串可以转换为ASII码

2.先将要字符串排序,即abc , acb , cba, bac 等,经过排序后都是abc

3.使用哈希表将排序后的字符串作为key,后续相同的作为value存储

4.最后遍历哈希表即可解决,unordered_map<string,vector<string>>,key为排序后的字符串,value为原字符串

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> dict;
        for (auto &str : strs)
        {
            string key = str;
            sort(key.begin(), key.end());
            dict[key].push_back(move(str));
        }

        vector<vector<string>> res;
        for (auto i = dict.begin(); i != dict.end(); i ++ )
        {
            res.push_back(move(i -> second));
        }

        return res;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

༄yi笑奈何

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值