专题十_哈希表

目录

题型总结

1. 两数之和

解析

题解

面试题 01.02. 判定是否互为字符重排

解析

题解

217. 存在重复元素

解析

题解

219. 存在重复元素 II

解析

题解

49. 字母异位词分组 

解析

题解


题型总结

1. 两数之和

1. 两数之和

解析

题解

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // 60.专题十_哈希表_两数之和_C++
        unordered_map<int, int> hash;
        for(int i = 0; i < nums.size(); ++i)
        {
            int x = target - nums[i];
            if(hash.count(x)) return {i, hash[x]};
            hash[nums[i]] = i;
        }
        return {-1, -1};
    }
};

面试题 01.02. 判定是否互为字符重排

面试题 01.02. 判定是否互为字符重排

解析

题解

class Solution {
public:
    bool CheckPermutation(string s1, string s2) {
        // 61.专题十_哈希表_判定是否互为字符重排_C++
        if(s1.size() != s2.size()) return false;
        int hash[26] = {0};
        for(auto ch1 : s1)
            hash[ch1 - 'a']++;
        for(auto ch2 : s2)
        {
            hash[ch2 - 'a']--;
            if(hash[ch2 - 'a'] < 0) return false;
        }
        return true;
    }
};

217. 存在重复元素

217. 存在重复元素

解析

题解

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        // 62.专题十_哈希表_存在重复元素I_C++
        unordered_set<int> hash;
        for(auto x : nums)
        {
            if(hash.count(x))  return true;
            else hash.insert(x);
        }
        return false;
    }
};

219. 存在重复元素 II

219. 存在重复元素 II

解析

题解

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        // 63.专题十_哈希表_存在重复元素II_C++
        unordered_map<int, int> hash;
        int n = nums.size();
        for(int i = 0; i < n; ++i)
        {
            if(hash.count(nums[i]) && abs(hash[nums[i]] - i) <= k) return true;
            else hash[nums[i]] = i;
        }
        return false;
    }
};

49. 字母异位词分组 

49. 字母异位词分组

解析

题解

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        // 64.专题十_哈希表_字母异位词分组_C++
        unordered_map<string, vector<string>> hash;
        // 1.把所有的字母异位词分组
        for(auto& s : strs)
        {
            string tmp = s;
            sort(tmp.begin(), tmp.end());
            hash[tmp].push_back(s);
        }

        // 2.结果提取出来
        vector<vector<string>> ans;
        for(auto& [x, y] : hash)
        {
            ans.push_back(y);
        }
        return ans;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

清风玉骨

爱了!

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

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

打赏作者

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

抵扣说明:

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

余额充值