【代码随想录训练营】【Day 6】【哈希表-1】| Leetcode 242, 349, 202, 1

【代码随想录训练营】【Day 6】【哈希表-1】| Leetcode 242, 349, 202, 1

需强化知识点

  • Python dict 的 get 方法,以及遍历方法

  • Python set 会自动去重

题目

242. 有效的字母异位词

  • 注意 python ord() 可以直接返回字符的unicode数值,chr() 可以将 unicode值转换为字符
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # record = [0] * 26

        # for c in s:
        #     record[ord(c) - ord('a')] += 1
        # for c in t:
        #     record[ord(c) - ord('a')] -= 1
        # for num in record:
        #     if num != 0:
        #         return False
        # return True

        from collections import defaultdict
        s_dict = defaultdict(int)
        t_dict = defaultdict(int)

        for c in s:
            s_dict[c] += 1
        for c in t:
            t_dict[c] += 1
        return s_dict == t_dict

349. 两个数组的交集

  • python dict 的循环遍历
  • python set 增加元素是用add,以及dict删除元素 del,get方法可以替代defaultdict
class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # from collections import defaultdict
        # num_dict = defaultdict(int)
        # result = []

        # for num in nums1:
        #     num_dict[num] += 1
        
        # for key, value in num_dict.items():
        #     if key in nums2:
        #         result.append(key)

        # return result

        num_dict = {}
        for num in nums1:
            num_dict[num] = num_dict.get(num, 0) + 1
        
        result = set()
        for num in nums2:
            if num in num_dict:
                result.add(num)
                # del num_dict[num]
        
        return list(result)

202. 快乐数

  • 注意无限循环停止判定的条件:出现历史上的曾出现的数
class Solution:
    def isHappy(self, n: int) -> bool:
        def num_square(n):
            num_list = []
            new_num = 0
            while n > 0:
                new_num += (n % 10) * (n % 10)
                n = n // 10
            return new_num
        
        num_dict = {}
        while True:
            new_num = num_square(n)
            if new_num == 1:
                return True
            if new_num in num_dict:
                return False
            else:
                num_dict[new_num] = 1
            n = new_num        

1. 两数之和

  • 注意hash_dict 加数要在判定之后,不然如果target等于 2*num, 会将自身视为另一个数
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashdict = {}
        for index, num in enumerate(nums):
            # hashdict[num] = index
            if target - num in hashdict:
                return [index, hashdict[target-num]]
            hashdict[num] = index
            
       
  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值