题目
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.
解题思路
将A B两个数组两两相加,C D两个数组两两相加,转换成2sum
代码
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
ct = defaultdict(int)
for a in A:
for b in B:
ct[a + b] += 1
res = 0
for c in C:
for d in D:
if -(c + d) in ct:
res += ct[-(c + d)]
return res