LeetCode--4Sum II(4个数的和)Python

本文介绍了一种高效解决四数组求和等于零的问题的方法。通过使用哈希表存储两个数组的所有可能组合之和,然后查找剩余两个数组的和是否为前者的负数,从而快速得出所有满足条件的组合数量。

题目:

给定四个长度为N的数组:A、B、C、D,找到A[i]+B[j]+C[k]+D[l]=0的tuple个数。

解题思路:

直接对四个数组进行遍历,时间复杂度为N的4次方,超时。之后想到将哈希应用到计算过程中。先将其中两个数组的和存储到字典中,再计算另外两个数组的和的相反数有没有在之前的字典中出现,出现则将最终的count数加上其出现的次数。时间复杂度为n的2次方。

代码(Python):

class Solution(object):
    def fourSumCount(self, A, B, C, D):
        """
        :type A: List[int]
        :type B: List[int]
        :type C: List[int]
        :type D: List[int]
        :rtype: int
        """
        count = 0
        n = len(A)
        Dict = {}
        for i in range(n):
            for j in range(n):
                temp = A[i]+B[j]
                if temp in Dict:
                    Dict[temp] = Dict[temp]+1
                else:
                    Dict[temp] = 1
        for i in range(n):
            for j in range(n):
                temp = -(C[i]+D[j])
                if temp in Dict:
                    count = count + Dict[temp]
                else:
                    continue
        return count

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值