给定四个包含整数的数组列表 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
思路1: 暴力搜索(O(n^4), 超时)
思路2: 暴力(优化最优一个数组的遍历, O(n^3*logn), 超时)
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
res = 0
D = list(sorted(D))
for i in range(len(A)):
for j in range(len(B)):
for k in range(len(C)):
summ = A[i] + B[j] + C[k]
l, r = 0, len(D) - 1
while l <= r:
mid = (l + r) // 2
if summ + D[mid] > 0:
r = mid - 1
elif summ + D[mid] < 0:
l = mid + 1
else:
res += D.count(D[mid])
break
return res
思路3: (分成两组求和),空间换时间, O(n^2))
这个思路,我没有想到,是参考的网上的题解。
from collections import Counter
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
dict = Counter([a + b for a in A for b in B])
res = sum([dict.get(-c-d, 0) for c in C for d in D])
return res