0
点赞
收藏
分享

微信扫一扫

C++ 哈希表OJ

caoxingyu 2024-03-07 阅读 22

目录

1、1. 两数之和

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

 3、217. 存在重复元素

4、 219. 存在重复元素 II

5、49. 字母异位词分组


1、1. 两数之和

 

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

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

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

 3、217. 存在重复元素

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_set<int> hash;
        for (auto n : nums) {
            if (hash.count(n))
                return true;
            else
                hash.insert(n);
        }
        return false;
    }
};

4、 219. 存在重复元素 II

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

5、49. 字母异位词分组

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

相关推荐

0 条评论