题目:
给定四个长度为N的数组:A、B、C、D,找到A[i]+B[j]+C[k]+D[l]=0的tuple个数。
解题思路:
直接对四个数组进行遍历,时间复杂度为N的4次方,超时。之后想到将哈希应用到计算过程中。先将其中两个数组的和存储到字典中,再计算另外两个数组的和的相反数有没有在之前的字典中出现,出现则将最终的count数加上其出现的次数。时间复杂度为n的2次方。
代码(Python):
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
"""
count = 0
n = len(A)
Dict = {}
for i in range(n):
for j in range(n):
temp = A[i]+B[j]
if temp in Dict:
Dict[temp] = Dict[temp]+1
else:
Dict[temp] = 1
for i in range(n):
for j in range(n):
temp = -(C[i]+D[j])
if temp in Dict:
count = count + Dict[temp]
else:
continue
return count