0
点赞
收藏
分享

微信扫一扫

454. 四数相加 II

杰森wang 2022-04-01 阅读 104
python

算法-目录
题目来源:Leetcode 454. 四数相加 II

454. 四数相加 II

在这里插入图片描述

解法1
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
        """
        # Counter类是dict()子类, 用于计数可哈希对象
        # 它是一个集合,元素像字典键(key)一样存储,它们的计数存储为值
        countAB=collections.Counter(u+v for u in nums1 for v in nums2)
        ans=0
        for u in nums3:
            for v in nums4:
                if -u-v in countAB:#是否出现过
                    ans+=countAB[-u-v]#累加出现的次数
        return ans
解法2[K]
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
        """
        res = 0
        dict = {}
        for a in nums1:
            for b in nums2:
                sum1 = a + b
                dict[sum1] = dict.get(sum1, 0) +1
        for c in nums3:
            for d in nums4:
                sum2 = c + d
                if -sum2 in dict:
                    res += dict[-sum2]           
        return res
举报

相关推荐

0 条评论