哈希表(5题)

目录

1.两数之和

2.判定是否互为字符重排

3.存在重复元素

4.存在重复元素2

5.字母异位词分组


1.两数之和

. - 力扣(LeetCode)

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

我们只需要一边判定一边把数组中的内容往里面塞即可 

2.判定是否互为字符重排

. - 力扣(LeetCode)

class Solution {
public:
    bool CheckPermutation(string s1, string s2) {
        if(s1.size() != s2.size())return false;
        int arr[128];
        for(auto ch:s1)
        {
            arr[ch]++;
        }
        for(auto ch:s2)
        {
            arr[ch]--;
            if(arr[ch]<0)return false;
        }
        return true;
    }
};

3.存在重复元素

. - 力扣(LeetCode)

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_map<int,int>hash;
        for(auto ch:nums)
        {
            if(hash.count(ch))return true;
            hash[ch]++;
        }
        return false;
    }
};

思路同1,一边判断一边把数塞进去

4.存在重复元素2

. - 力扣(LeetCode)

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int,int>hash;
       for(int i = 0; i < nums.size(); i++)
       {
         int x = nums[i];
         if(hash.count(x) &&  i - hash[x] <= k)return true;
         hash[x] = i;
       }
        return false;
    }
};

5.字母异位词分组

. - 力扣(LeetCode)

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
       unordered_map<string,  vector<string>  >hash;
       vector<vector<string>>ret;
        for(auto ch: strs)
        {
            string tmp = ch;
            sort(tmp.begin(),tmp.end());
            hash[tmp].push_back(ch);
        }
        for(auto [x,y]: hash)
        {
            ret.push_back(y);
        }
        return ret;
    }
};

        把异位词字符串排好序之后都是一样的,所以我们把排完以后相同的字符串作为标志,把这些字符串一个个填进去

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值