代码随想录算法训练营day 6| 454 四数之和ii,383 赎金信

454 四数之和ii

  1. 创建一个哈希映射 sum_ab,用来存储 nums1 + nums2 的和及其出现次数。
  2. 遍历 nums1 和 nums2 的所有元素组合,将它们的和作为键存储在 sum_ab 中,并统计该和出现的次数。
  3. 遍历 nums3 和 nums4 的所有元素组合,在每一次迭代中,计算 nums3[i] + nums4[j] 的和的相反数 target。
  4. 检查 target 是否存在于 sum_ab 的键中,如果存在,则将对应的值累加到结果中。
  5. 返回最终的结果。
class Solution(object):
    def fourSumCount(self, nums1, nums2, nums3, nums4):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :type nums3: List[int]
        :type nums4: List[int]
        :rtype: int
        """

        result = 0
        sum_map = {}
        for i in nums1:
            for j in nums2:
                sum_map[i+j] = sum_map.get(i+j,0)+1
        
        for k in nums3:
            for l in nums4:
                target = -(k+l)
                if target in sum_map:
                    result += sum_map[target]
        return result

383 赎金信

  1. 创建一个哈希映射 wordMap,用于存储 ransomNote 中每个字符的出现次数。
  2. 遍历 ransomNote,对于每个字符,将其作为键,将其在 wordMap 中的计数加一。
  3. 遍历 magazine,对于每个字符,将其作为键,将其在 wordMap 中的计数减一。
  4. 遍历 wordMap 中的所有值,如果存在任何值小于零,表示 magazine 中的某个字符出现次数不足以构建 ransomNote,返回 False。
  5. 如果循环结束后没有返回 False,则说明 magazine 中的字符出现次数足够构建 ransomNote,返回 True。
class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        wordMap = {}
        for char in ransomNote:
            wordMap[char] = wordMap.get(char, 0) + 1
        for char in magazine:
            wordMap[char] = wordMap.get(char, 0) - 1

        for count in wordMap.values():
            if count > 0:
                return False

        return True

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值