给定四个包含整数的数组列表 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 。所有整数的范围在 -2^28 到 2^28 - 1 之间,最终结果不会超过 2^31 - 1 。
例如:
输入:
- A = [ 1, 2]
- B = [-2,-1]
- C = [-1, 2]
- D = [ 0, 2]
输出:
2
解释:
两个元组如下:
- (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
- (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
思路:
首先定义一个dict,key是a+b的元素和,value是同一个和出现的次数。
定义count=0,用来统计个数。
遍历c和d,如果0-(c+d)在dict中出现过,就把count+= (a+b)对应的value
最后返回count
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
res = {}
for i in nums1:
for j in nums2:
if i+j not in res:
res[i+j] = 1
else:
res[i+j] += 1
count = 0
for i in nums3:
for j in nums4:
if 0-(i+j) in res:
count += res[0-(i+j)]
return count
特别注意:
第一个if statement: 如果i+j不在res,则res[i+j]=1,而不是=0
if i+j not in res:
res[i+j] = 1
else:
res[i+j] += 1
这一部分也可以改写成:
res[i+j] = res.get(i+j,0)+1
意思是,如果res里面没有key=i+j, 就让它有,并且对应的value=0.
如果res里有key=i+j, 就让它对应的value +1