[LeetCode]454. 4Sum II

454. 4Sum II

题意:从给定的数组中统计四个数相加和为0的个数

思路:用哈希表来保存,四个数分成两部分,统计双方和的个数,最后相加。

import collections
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
        """
        number = collections.defaultdict(int)
        l = len(A)
        for i in range(l):
            for j in range(l):
                number[A[i]+B[j]] += 1
        res = 0
        for i in range(l):
            for j in range(l):
                neg = -1 * (C[i]+D[j])
                res += number[neg]
        return res
posted @ 2017-09-12 09:40  banananana  阅读(122)  评论(0编辑  收藏  举报