算法训练营 day5 | 哈希表part01

242.有效的字母异位词

题目链接

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        hash = [0 for _ in range(26)] # 初始化hash表
        for i in s: # 将对应i的ascii码相对于‘a’作为下标存到hash数组中
            hash[ord(i) - ord('a')] += 1
        for i in t:
            hash[ord(i) - ord('a')] -= 1
        for i in range(26):
            if hash[i] != 0:
                return False
        return True

总结:ord()是转换成ascii码。减去‘a’是为了方便作为下标进行映射。如果两个字符串有不同的字母,那么hash表中一定不全为零。

349. 两个数组的交集

题目链接

解法一:数组解法

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        res = []
        hash = [0] * 10001
        for i in nums1:
            if hash[i] == 0:
                hash[i] += 1
        for i in nums2:
            if hash[i] == 1:
                hash[i] += 1
        for i in range(1001):
            if hash[i] > 1:
                res.append(i)
        return res

解法二:set+数组

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        table = {}
        for num in nums1:
            table[num] = table.get(num, 0) + 1  # 记录每个值及出现的次数
        print(table)
        res = set()
        for num in nums2:
            if num in table:
                res.add(num)
                del table[num]
        return list(res)

总结:数组解法和上一题的思路类似,在nums1中出现的hash表对应为1,在nums2中重复出现的变为2,在hash表中过滤大于1的即可。

set+数组解法:把nums1出现的数字以及出现的次数存到字典中,然后查询nums2中的数字是否出现在字典中,出现就添加到结果集合中,然后删除对应字典中的值。利用了set不会出现重复元素的特性。

202. 快乐数

题目链接

class Solution:
    def isHappy(self, n: int) -> bool:
        record = set()
        while n not in record:
            record.add(n)
            new_num = 0
            new_str = str(n)
            for i in new_str:
                new_num += int(i) ** 2
            if new_num == 1:
                return True
            else:
                n = new_num 
        return False

总结:重点在于要先让数字转换成字符串方便处理。如果经过计算的数重复出现那一定是陷入了死循环,不会满足快乐数的要求

1. 两数之和

题目链接

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        records = {}

        for index, value in enumerate(nums):
            if target - value in records:  # 遍历当前元素,并在map中寻找是否有匹配的key
                return [records[target-value], index]
            records[value]=index. # 如果没找到匹配对,就把访问过的元素和下标加入到map中
        return []

你可能感兴趣的:(算法训练营 day5 | 哈希表part01)