题目:四数相加 II
给定四个包含整数的数组列表 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
----------------------------------------------------------------
思路:考虑到时间复杂度问题,直接遍历4个列表的值,依次相加,存在大量的重复,肯定超时。
解法1#:通过构建字典的方式,将AB的 "和" 存入字典,字典的值为出现这个"和" 出现的次数。
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
"""
# 方法1
count = 0
dic_AB = {}
for num1 in A:
for num2 in B:
if (num1+num2) in dic_AB:
dic_AB[num1+num2] += 1
else:
dic_AB[num1 + num2] = 1
for num3 in C:
for num4 in D:
if -(num3+num4) in dic_AB:
count += dic_AB[-(num3+num4)]
return count
解法2:解法1的另一种写法
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
dic_AB = {}
for num1 in A:
for num2 in B:
dic_AB[num1+num2] = dic_AB.get(num1+num2, 0) + 1
for num3 in C:
for num4 in D:
if -(num3+num4) in dic_AB:
count += dic_AB[-(num3+num4)]
return count
解法3#:使用python自带的defaultdict
defaultdict 的其他功能与dict相同,但会为一个不存在的键提供默认值,从而避免KeyError异常。
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
"""
from collections import defaultdict
count = 0
dd = defaultdict(int)
for num1 in A:
for num2 in B:
tot = num1+num2
dd[tot] += 1
for num3 in C:
for num4 in D:
tot = -(num3+num4)
count += dd[tot]
return count
参考:
https://blog.csdn.net/u014248127/article/details/79338543
https://blog.csdn.net/qq_32424059/article/details/88698903