哈希表专题

题解之前:

1.有关unordered_map的count功能:查询key!

Leetcode 1.两数之和

 解题思路:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        // key:具体的数值(便于count查看是否存在) value:具体的下标索引idx(ans)
        unordered_map<int, int> s;     
        for(int i = 0; i < nums.size(); i ++){
            int left =  target - nums[i];
            if(s.count(left)){   // 已经存在了
                res.push_back(i); res.push_back(s[left]);
                break;
            }
            s[nums[i]] = i;
        }
        return res;
    }
};

Leetcode 454.四数相加 II

解题思路:

代码:

class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
        int res = 0;
        unordered_map<int, int> s;
        for(auto a: nums1)
            for(auto b: nums2)
                s[a + b] ++;
        
        for(auto c: nums3)
            for(auto d: nums4)
                res += s[-c - d]; 
        return res;
    }
};

 Leetcode 49.字母异位词分组 

算法核心:选择什么作为哈希表的key?

解法一:排序+hash

 

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> ans;
        unordered_map<string, int> s;
        int idx = -1;
        for(auto v: strs){
            string cp = v;
            sort(v.begin(), v.end());
            if(!s.count(v)){
                vector<string> t = {cp};
                ans.push_back(t);
                s[v] = ++ idx;
            }else{
                ans[s[v]].push_back(cp);
            }
        }
        return ans;
    }
};

解法二:计数+hash

 

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        int idx = -1;
        vector<vector<string>> ans;
        unordered_map<string, int> map;
        for(auto v: strs){
            vector<int> cnt(26, 0);  // 计数数组
            // 初始化计数数组
            for(char c: v)
                cnt[c - 'a'] ++;
            // 生成字符串key
            string key = "";
            for(int i = 0; i < 26; i ++){
                key += 'a' + i;
                key += cnt[i];
            }
            // 看看是否出现过
            if(!map.count(key)){    // 没有出现过
                vector<string> t = {v};
                ans.push_back(t);
                map[key] = ++ idx;
            }else                   // 出现过
                ans[map[key]].push_back(v);
        }
        return ans;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_Ocean__

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

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

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

打赏作者

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

抵扣说明:

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

余额充值