这题的解题过程,直接用四个for循环去暴力解的话时间复杂度太高,通过将前两个数组合并(各个数相加)成一个字典,后两个数组合并(各个数相加)成一个字典从而降低时间复杂度。为什么合并成字典,是因为合并之后出现的相同数字要算上次数。在此不熟悉的可以查一下数组和字典的区别。
class Solution(object):
def fourSumCount(self, nums1, nums2, nums3, nums4):
# 使用字典存储nums1和nums2中的元素及其和
hashmap = dict()
for n1 in nums1:
for n2 in nums2:
if n1 + n2 in hashmap:
hashmap[n1+n2] += 1
else:
hashmap[n1+n2] = 1
# 如果 -(n1+n2) 存在于nums3和nums4, 存入结果
count = 0
for n3 in nums3:
for n4 in nums4:
key = - n3 - n4
if key in hashmap:
count += hashmap[key]
return count
2041

被折叠的 条评论
为什么被折叠?



