454 四数相加2
给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
重点在于先去把前两个数组加和情况做统计,保存到map中,value是加和值出现的次数。然后在统计后两个数组加和的情况,在a+b的map中做查找,看有没有0-(c+d)的值,有的话,count加上其相应的value次数,而不是只加1,要注意。最后返回count。
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
count = 0
count12 = {}
for i in nums1:
for j in nums2:
if i+j not in count12.keys():
count12[i+j] = 1
else:count12[i+j] += 1
for x in nums3:
for y in nums4:
if 0-(x+y) in count12.keys():
count += count12[0-x-y]
return count