题目:
给定四个包含整数的数组列表 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
分析:
总共四个数组,简单的暴力做法是一层一层遍历数组里的元素,拿到所有的组合,将计算的值和0进行对比。
这样的时间复杂度是O(n^4)
代码很简单,直接四层循环:
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
result = 0
for i in A:
for j in B:
for k in C:
for l in D:
if i+j+k+l == 0:
result += 1
return result
不出意外,超出了时间限制。
如何减少时间复杂度?
将四层循环减少一下,比如可以先将两个数组的值相加,得到一组和,另外两个数组相加再得到一组和。 最后将这两组和进行相加。这样时间复杂度是变成n*n + n*n + n*n
。这样看下来,确实少了很多。
代码如下:
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
result,preList,sufList = 0,[],[]
for i in A:
for j in B:
preList.append(i+j)
for k in C:
for l in D:
sufList.append(k+l)
for pre in preList:
for suf in sufList:
if pre + suf == 0:
result +=1
return result
但是还是超出了时间限制……
后来一想,上面的复杂度虽然变成了O(n^2),但是忘记考虑最后两个数组相加的时候,n已经不是之前的n了。所以最终下来的时间复杂度还是很高。所以应该想办法避免最后两个数组相加的情况。
可以考虑先存下来前两个数组的和,然后再去遍历后面两个数组。这样复杂度就是 O(n^2),并且n还是之前的n
最终代码:
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
result,mapDic = 0,{}
for i in A:
for j in B:
if i+j in mapDic:
mapDic[i+j] += 1
else :
mapDic[i+j] = 1
for k in C:
for l in D:
if -k-l in mapDic:
result += mapDic[-k-l]
return result
网友评论