思路1:哈希表
前面的四数相加使用了双指针,但是本题是多个列表,无法使用。考虑使用哈希表,最好的情况是使用两个哈希表,分别存两个数组的和,再检查是否存在。当然,实际上只用一个哈希表就行了。
时间复杂度O(n2)
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
# 使用字典存储前两个数组的和
sumdic1 = {}
for a in A:
for b in B:
sumval = a+b
if not sumval in sumdic1:
sumdic1[sumval]=1
else:
sumdic1[sumval]+=1
# 检验CD元素和是否在字典中,把存在值的次数相加
return sum(sumdic1[-c-d] for c in C for d in D if (-c-d) in sumdic1)