0
点赞
收藏
分享

微信扫一扫

Think PHP6+Swagger3

墨香子儿 2023-06-12 阅读 106

Day 6 哈希表

哈希表理论基础

解决哈希碰撞的方法:

  1. 拉链法
  2. 线性探测法

242. 有效的字母异位词

有一个坑:两个单词包含的字母个数必须相同,精确到特定单词的个数。如果不考虑这一点,会在一些案例上出错,比如s=[ab], t=[a]或者s=[abcd], t=[aaaa],这两个案例的正确答案都是false,直接使用unordered_set可能没办法解决这一问题。

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) return false;
        
        unordered_map<char, int> table;

        for (auto &c : s)
        {
            table[c]++;
        }

        for (auto &c : t)
        {
            table[c]--;
        }

        for (auto &[c, n] : table)
        {
            if (n != 0)
            {
                return false;
            }
        }

        return true;
    }
};

349. 两个数组的交集

题目要求:输出结果中的每个元素一定是 唯一 的。所以得先用unordered_set去重,然后再转换成vector

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> table;
        unordered_set<int> ret;

        for (auto num : nums1)
        {
            table.insert(num);
        }

        for (auto num : nums2)
        {
            if (table.find(num) != table.end())
            {
                ret.insert(num);
            }
        }

        return vector<int>(ret.begin(), ret.end());
    }
};

202. 快乐数

class Solution {
    int calc(int n)
    {
        int rst = 0;
        while (n)
        {
            int re = n  % 10;
            rst += re * re; 
            n /= 10;
        }

        return rst;
    }

public:
    bool isHappy(int n) {
        unordered_set<int> table;

        while (true)
        {
            int rst = calc(n);
            if (rst == 1)
            {
                return true;
            }
            else if (table.find(rst) != table.end())
            {
                return false;
            }
            else
            {
                table.insert(rst);
            }
            n = rst;
        }
        
        return false;
    }
};

1. 两数之和

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> table;

        for (int i = 0; i < nums.size(); i++)
        {
            auto iter = table.find(target - nums[i]);
            if (iter != table.end())
            {
                return {i, iter->second};
            }
            else
            {
                table[nums[i]] = i;
            }
        }
        return {};
    }
};
举报

相关推荐

0 条评论