给定四个包含整数的数组列表 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
第一种思路:
观察一下,如果直接暴力解, 四重循环时间复杂度为 N ^4,有点大难以接受。
再看题意要求找到和为0的四个数,等价于从AB里找到一个和,再从CD里找到另一个和,这两个和互为相反数,这样就可以把时间复杂度从N^4 降低到N^2。
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
"""
map1 = list()
res = 0
for a in A:
for b in B:
map1.append(a + b)
for c in C:
for d in D:
t = c + d
if t in map1:
res += map1.count(t)
return res
上面的代码超时了,过不了最后一个CASE。原因:每次都要count一下太浪费时间了,做了很多重复的工作。
所以有下面的优化:
用dict去存,key是和,value是出现的次数,这样就不用count了,可以通过。
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
"""
map1 = dict()
res = 0
for a in A:
for b in B:
t = a + b
map1[t] = map1.get(t, 0) + 1
for c in C:
for d in D:
t = - c - d
if t in map1:
res += map1[t]
return res
进一步优化:
用defaultdict 代替dict,就不用判断每次key存不存在,可以直接调用defaultdict【key】。
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
"""
from collections import defaultdict
map1 = defaultdict(int)
res = 0
for a in A:
for b in B:
t = a + b
map1[t] += 1
for c in C:
for d in D:
t = - c - d
res += map1[t]
return res