【leetcode刷刷】242.有效的字母异位词 、349. 两个数组的交集、202. 快乐数、1. 两数之和

哈希

解决哈希碰撞的方法:

  • 拉链法:链表
  • 线性探测法:冲突的用下一个位置来放

哈希的底层实现还不是很明白

242. 有效的字母异位词

  1. python里面使用哈希表,使用dict或者defaultdict或者{}
  2. table[num] = table.get(num, 0) + 1。这样就不用if判断是否在哈希表里了。table.get(num, 0),不存在就是0
  3. 计算字符串中字母出现的次数可以使用Counter
  4. ACII码的计算:ord(i) - ord(“a”)
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # 1. 使用dict:dict和defaultdict有啥区别
        count_s = dict()
        count_t = dict()
        for i in s:
            if i in count_s:
                count_s[i] += 1
            else:
                count_s[i] = 1
            # table[num] = table.get(num, 0) + 1
        for i in t:
            if i in count_t:
                count_t[i] += 1
            else:
                count_t[i] = 1
        return count_s == count_t

        # 2。使用counter
        count_s = Counter(s)
        count_t = Counter(t)
        return count_s == count_t

        # 3. 26个字母分别记录.
        # ACII码的计算:ord(i) - ord("a")

349. 两个数组的交集

  1. 几个小优化:table[num] = table.get(num, 0) + 1
  2. 只需要第一个nums1构建哈希表,nums2遍历的时候去哈希表找就行,不需要两个nums都构建哈希表,可以减少一次遍历
  3. del table[num]

代码随想录的解答:

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
        
        # 使用集合存储结果
        res = set()
        for num in nums2:
            if num in table:
                res.add(num)
                del table[num]
        
        return list(res)

自己写的:

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        count1 = Counter(nums1)
        count2 = Counter(nums2)
        output = []
        for i in count1:
            if i in count2:
                output.append(i)
        return output

202. 快乐数

  1. 为了防止循环需要把sum记录下来,出现循环就表示不是快乐数
class Solution:
    def isHappy(self, n: int) -> bool:
        sum = 0
        sum_set = set()
        while(sum != 1):
            sum = 0
            for i in str(n):
                sum += int(i)**2
            if sum in sum_set:
                return False
            else:
                sum_set.add(sum)
                n = sum
        return True

1. 两数之和

  1. 原来第一题这么难的吗。一时还没想到非暴力的解法。
  2. 用dict来记录遍历过的数字,之后就可以用哈希表查找了,可以防止再遍历一遍,用空间O(n)换时间O(n)
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        num_set = dict()
        for i in range(len(nums)):
            find = target - nums[i]
            if find in num_set:
                return [num_set.get(find), i]
            num_set[nums[i]] = i   # key是数字,value是位置
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值