自学内容网 自学内容网

【C++算法】哈希表

哈希表介绍:

1.哈希表是什么?

存储数据的容器 

2.哈希表有什么用?

“快速”查找某个元素——O(N)

3.什么时候使用哈希表?

频繁的查找某一个数的时候,频繁也可以使用二分(有序)

4.怎么用哈希表?

 1.容器(哈希表)

2.用数组模拟简易哈希表

  • 字符串中的“字符”
  • 数据范围很小的时候

俩数之和

  • 题目链接

俩数之和icon-default.png?t=O83Ahttps://leetcode.cn/problems/two-sum/submissions/565694047/

  • 算法原理

  • 代码展示
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hashi;
        for(int i = 0; i < nums.size(); i++)
        {
             if(hashi.find(target - nums[i])!= hashi.end())
             {
                  return {hashi[target - nums[i]], i};
             }
            hashi[nums[i]] = i;
        }
        return {-1, -1};
    }
};

判定是否互为字符重排

  • 题目链接

判定是否互为字符重排icon-default.png?t=O83Ahttps://leetcode.cn/problems/check-permutation-lcci/description/

  • 算法原理

  • 代码展示
class Solution 
{
public:
    bool CheckPermutation(string s1, string s2) 
    {
        if(s1.size() != s2.size()) return false;
        int hash[26] = { 0 };
        for(int i = 0; i < s1.size(); i++)
        {
            hash[s1[i] - 'a']++;
        }

        for(int i = 0; i < s2.size(); i++)
        {
            hash[s2[i] - 'a']--;
            if(hash[s2[i] - 'a'] < 0) return false;
        }

        return true;

    }
};

存在重复元素I

  • 题目链接

存在重复元素Iicon-default.png?t=O83Ahttps://leetcode.cn/problems/contains-duplicate/description/

  • 算法原理

解法:哈希表

  • 代码展示
class Solution 
{
public:
    bool containsDuplicate(vector<int>& nums) 
    {
        unordered_set<int> hash;
        for(int i = 0; i < nums.size(); i++)
        {
            if(hash.count(nums[i])) return true;
            else hash.insert(nums[i]);
        }

        return false;
    }
};

存在重复元素II

  • 题目链接

存在重复元素IIicon-default.png?t=O83Ahttps://leetcode.cn/problems/contains-duplicate-ii/description/

  • 算法原理

  • 代码展示
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]) && i - hash[nums[i]] <= k) return true;
            else hash[nums[i]] = i;
        }
        return false;
    }
};

字母异位词分组

  • 题目链接

字母异位词分组icon-default.png?t=O83Ahttps://leetcode.cn/problems/group-anagrams/

  • 算法原理

  • 代码展示
class Solution 
{
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) 
    {
        unordered_map<string, vector<string>> hash;
        for(int i = 0; i < strs.size(); i++)
        {
            // 排序
            string tmp = strs[i];
            sort(tmp.begin(), tmp.end());
            // 添加
            hash[tmp].push_back(strs[i]);
        }

        vector<vector<string>> ret;
        for(auto& [x, y] : hash)
        {
            ret.push_back(y);
        }

        return ret;
    }
};

原文地址:https://blog.csdn.net/dab112/article/details/142336643

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!