给定四个包含整数的数组列表 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 。
例如:
输入:
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
思路:类似于leetcode第1题,利用查找表的方法,将C+D所有的可能结果放在字典中作为key,value为可能的组合个数,再去遍历A+B所有的可能取值,如果等于某个0-C-D的值则统计可能的组合情况(加上C+D可能取0-C-D时的个数)
扫描二维码关注公众号,回复:
9861020 查看本文章
由于N最大为500,因此查询表维度为250000可以接受
时间复杂度:O(n^2)
空间复杂度:O(n^2)
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
"""
record = dict()
for c in C:
for d in D:
record[c + d] = 0
for c in C:
for d in D:
record[c + d] = record[c + d] + 1
result = 0
for a in A:
for b in B:
if record.has_key(0 - a - b): # 此时满足四个数相加为0
result = result + record[0 - a - b]
return result