day6哈希表的应用

242有效的字母异位词

要求出现频次相同,使用一个数组记录s的字母出现次数,对应s中的字符频次++,对于t中的频次--,如果s和t的字母组合相同,则最终的数组应该是全零。

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size() != t.size()) {
            return false;
        }
        int table[26] = {0};
        for(int i = 0; i < s.size(); ++i) {
            table[s[i]-'a']++;
            table[t[i]-'a']--;
        }
        for(int i = 0; i < 26; ++i) {
            if(table[i] != 0) {
                return false;
            }
        }
        return true;
    }
};

349. 两个数组的交集

如果nums1中出现了字符c且nums2中也出现了字符c,则c应该在nums1∩nums2中,所以把nums1中出现的字符记录一下,并且在nums2中对比,如果出现了就说明相交
这里有个小坑,就是在遍历的时候,可能会出现重复出现的字符,这个时候如果直接push_back会导致重复,我们可以使用unordered_set去重

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int, bool> table;
        for(int i = 0; i < nums1.size(); ++i) {
            table[nums1[i]] = true;
        }
        unordered_set<int> ans;
        for(int i = 0; i < nums2.size(); ++i) {
            if(table[nums2[i]]) {
                ans.insert(nums2[i]);
            }
        }
        return vector<int>(ans.begin(), ans.end());
    }
};

202. 快乐数

这个题目的关键在于你要知道怎么判断出现循环了,也就是说在transform数字的过程中,什么情况会导致无穷无尽呢?出现回路了,也就是在变换的规程中出现了重复出现的数字,这里就可以用hash表记录,这题用的java,顺便复习下java语法。

class Solution {
    private int transform(int x) {
        int ret = 0;
        while(x != 0) {
            ret += (x % 10) * (x % 10);
            x /= 10;
        }
        return ret;
    }
    public boolean isHappy(int n) {
        Map<Integer, Boolean> table = new HashMap<Integer, Boolean>();
        while(true) {
            if(n == 1) {
                return true;
            }
            if(table.containsKey(n)) {
                return false;
            }
            table.put(n, true);
            n = transform(n);
        }
    }
}

最后一题是梦开始的地方(

1.两数之和

思路是在遍历的过程中把遇到的数字记录下来,下次判断我们需要什么数字的时候,这个遍历就是有用的。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // num, idx
        Map<Integer, Integer> table = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            if(table.containsKey(target - nums[i])) {
                return new int[] {i, table.get(target - nums[i])};
            }
            table.put(nums[i], i);
        }
        return new int []{-1, -1};
    }
}
posted @ 2024-01-01 14:59  ccnju  阅读(19)  评论(0)    收藏  举报