Leetocde 每日一题
题目链接: 454. 四数相加 II
难度: 中等
解题思路: 四个数组中的元素相加等于0的个数。若纯暴力四个for循环肯定是不行的。所以可以将四个数组划分成两个部分,每部分对两个数组进行加法预处理。这样可将时间复杂度降到 O(n^2)。
题解:
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
sum_ab = {}
for a in A:
for b in B:
sum_ab[a + b] = sum_ab.get(a + b, 0) + 1
res = 0
for c in C:
for d in D:
if -(c + d) in sum_ab:
res += sum_ab[-(c + d)]
return res