五月集训(第07天)—— 哈希表

哈希表

1. 1512. 好数对的数目

    思路:
        利用哈希表的方式索引,将每个数字与其出现次数建立映射。然后利用数学知识求出好数对的数目。某个数出现一次时对ans无影响,当再出现一个与当前出现的数组成一组,第三个出现的数与当前两个构成两个新的组,依次累加即可获得结果。

class Solution {
public:
    int numIdenticalPairs(vector<int>& nums) {
        int cnt[102];
        memset(cnt, 0, sizeof(cnt));
        int ans = 0;
        for (int num : nums) {
            ans += cnt[num];
            cnt[num]++;
        }
        return ans;
    }
};

2. 2006. 差的绝对值为 K 的数对数目

    思路:
        由于数据范围和每个数字的数值很小,所以将每个数字与其出现次数建立哈希映射。由数学知识可知,每个绝对值相差为k的数对个数是两个数字分别出现的次数的乘积。

class Solution {
public:
    int countKDifference(vector<int>& nums, int k) {
        int cnt[103];
        int ans = 0;
        memset(cnt, 0, sizeof(cnt));
        for (int num : nums)
            cnt[num] ++;
        for (int i = 1; i + k <= 100; i++) 
            ans += (cnt[i] * cnt[i + k]);
        return ans;
    }
};

3. 1347. 制造字母异位词的最小步骤数

    思路:
        将字符串t中每个字母出现的次数进行统计,并将每个字母与其出现次数建立映射关系。用字符串s中的每个字母去匹配t中字母,如果出现则不用替换(注意不要重复计数mmp[s[i] - 'a']),如果没有出现则增加一次替换,返回最终替换的次数。

class Solution {
public:
    int minSteps(string s, string t) {
        int len = s.length();
        int mmp[27];
        int ans = 0;
        memset(mmp, 0, sizeof(mmp));
        for (int i = 0; i < len; i++) mmp[t[i] - 'a'] ++;
        for (int i = 0; i < len; i++) {
            if (mmp[s[i] - 'a']) mmp[s[i] - 'a']--;
            else ans++;
        }
        return ans;
    }
};

4. 面试题 10.02. 变位词组

    思路:
        将每个单词与一个字符串建立映射关系,该字符串反映了单词的每个字母出现的次数,作为哈希的索引,利用C++中的unordered map建立字符串与字符串数组之间的映射,将反应单词字母出现次数的字符串相同的单词放入同一个字符串数组中。

笨手笨脚的模仿别人的题解用了用C++unordered map,一定要找时间学习C++

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector <vector<string>> ans;
        unordered_map <string, vector<string>> ss;
        int n = strs.size();
        
        for (int i = 0; i < n; i++) {
            string mmp = string(26, 0);
            int len = strs[i].length();
            for (int j = 0; j < len; j++) mmp[strs[i][j] - 'a']++;
            ss[mmp].push_back(strs[i]);
        }
        for(auto &c : ss) ans.push_back(c.second);

        return ans;
    }
};
posted @ 2022-05-08 17:58  番茄元  阅读(7)  评论(0)    收藏  举报