197 - 454 四数相加2

题目

给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。

为了使问题简单化,所有的 A, B, C, D 具有相同的长度 N,且 0 ≤ N ≤ 500 。所有整数的范围在 -228 到 228 - 1 之间,最终结果不会超过 231 - 1 。

例如:

输入: A = [ 1, 2] B = [-2,-1] C = [-1, 2] D = [ 0, 2]

输出: 2

解释: 两个元组如下: 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

解答

就是四数之和的变体,只不过每个数有自己固定的可选项

四个for循环吗哈哈哈哈哈

hash

https://leetcode.com/problems/4sum-ii/discuss/93927/python-O(n2)-solution-with-hashtable

class Solution:
    def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
        data = {}
        for a in A:
            for b in B:
                if a+b in data:
                    data[a+b] += 1
                else:
                    data[a+b] = 1
        count = 0
        for c in C:
            for d in D:
                if -c-d in data:
                    count += data[-c-d]
        return count

Runtime: 272 ms, faster than 78.97% of Python3 online submissions for 4Sum II.

Memory Usage: 33.6 MB, less than 100.00% of Python3 online submissions for 4Sum II.

python:我有一个方法。。。

https://leetcode.com/problems/4sum-ii/discuss/93917/Easy-2-lines-O(N2)-Python

class Solution:
    def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
        import collections
        dic = collections.Counter(a+b for a in A for b in B)
        return sum(dic.get(-c-d, 0)for c in C for d in D)

Runtime: 244 ms, faster than 97.10% of Python3 online submissions for 4Sum II.

Memory Usage: 33.7 MB, less than 100.00% of Python3 online submissions for 4Sum II.

Last updated

Was this helpful?