刷题 LeetCode哈希1

代码随想录

LeetCode 242. 有效的字母异位词

carl

哈希 #Unicode

思路

  • 用哈希表存储两个字符串中每个字符出现的次数
  • 比较

细节

  • 为什么不用STL中的unordered_map?
    • 大材小用了,使用STL可能哈希函数十分复杂,因此简单情况下更适合自行构造
  • 遇到unicode如何解决
    • unicode是多字节,就不适合自己实现哈希了,因为数量剧增,考虑采用容器std::map或std::unordered_map实现,键也不再是26个小写字母,而是C++表示unicode的方法--std::string
    • 可能会有这种疑惑根据utf8编码unicode多字节字符使用了不同于ASCII的字节格式,char能表示吗?这就要将char与ASCII进行区分了,ASCII共编码了127个字符,而char是一种数据类型,C/C++将其认为是一个8位整数,不只可以表示ASCII字符,事实上可以表示任何可以用二进制表示的内容。即不仅表示ASCII,还能表示Unicode。这也是char能存储二进制数据的原因
class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size() != t.size()){
            return false;
        }
        int arr[26] = {0};
        for(int i = 0; i < s.size(); ++i){
            ++arr[s[i] - 'a'];
        }
        for(int i = 0; i < t.size(); ++i){
            if(--arr[t[i] - 'a'] < 0){ //-----------------如果数目不同
                return false;
            }
        }
        return true;
    }
};

LeetCode 349. 两个数组的交集

carl

哈希

思路

  • 有具体范围且不算大,优先选数组
  • 没有具体范围用stl
    细节
class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        bool hashmap[1000] = {false};
        vector<int> res;
        res.reserve(1000);
        for(int i = 0; i < nums1.size(); ++i){
            hashmap[nums1[i]] = true;
        }
        for(int i = 0; i < nums2.size(); ++i){
            if(hashmap[nums2[i]]){
                res.push_back(nums2[i]);
                hashmap[nums2[i]] = false;
            }
        }
        return res;
    }
};

LeetCode 202. 快乐数
carl

哈希

思路

  • 用哈希记录出现过的数值,从而判断是否重复
    细节

LeetCode 1. 两数之和
思路

细节

  • 返回值写法
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> diff_map;
        for(int i = 0; i < nums.size(); ++i){
            if(diff_map.find(nums[i]) != diff_map.end()){
                return {diff_map[nums[i]], i};
            }
            diff_map.insert({target - nums[i], i});
        }
        return {};
    }
};
posted @ 2022-10-18 20:11  Nsf  阅读(27)  评论(0)    收藏  举报