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.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]
Output:
2
Explanation:
The two tuples are:
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

思路

由于结果不能重复,我们就以空间换时间,经历多层哈希表得到最终的结果。

把数组A、B、C、D里面的数字出现频率统计一番,接下来把A+B,C+D当中出现过的数字也进行统计。最后遍历统计后的AB, CD两个哈希表,得到结果。

时间复杂度由naive的O(n^4) 降低到最好情况为O(1), 平均下来应也有O(n^2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
"""
countA = {}
countB = {}
countC = {}
countD = {}
ans = 0
for i in A:
if (countA.has_key(i)):
countA[i] += 1
else:
countA[i] = 1
for i in B:
if (countB.has_key(i)):
countB[i] += 1
else:
countB[i] = 1
for i in C:
if (countC.has_key(i)):
countC[i] += 1
else:
countC[i] = 1
for i in D:
if (countD.has_key(i)):
countD[i] += 1
else:
countD[i] = 1
countAB = {}
for i in countA.keys():
for j in countB.keys():
if (countAB.has_key(i+j)):
countAB[i+j] += countA[i] * countB[j]
else:
countAB[i+j] = countA[i] * countB[j]
countCD = {}
for i in countC.keys():
for j in countD.keys():
if (countCD.has_key(i+j)):
countCD[i+j] += countC[i] * countD[j]
else:
countCD[i+j] = countC[i] * countD[j]
for i in countAB.keys():
if countCD.has_key(-i):
ans += countAB[i] * countCD[-i]
return ans

实际上直接这样就可以AC了……

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
"""
ans = 0
countAB = {}
for i in A:
for j in B:
if (countAB.has_key(i+j)):
countAB[i+j] += 1
else:
countAB[i+j] = 1
countCD = {}
for i in C:
for j in D:
if (countCD.has_key(i+j)):
countCD[i+j] += 1
else:
countCD[i+j] = 1
for i in countAB.keys():
if countCD.has_key(-i):
ans += countAB[i] * countCD[-i]
return ans