- 题目描述
给定四个包含整数的数组列表 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
- 思路
遍历A、B元素之和的所有可能情况,用字典来记录,字典的键为和的值,值为该和出现的次数
计算C、D元素之和的所有可能情况,判断如果C、D之和等于-AB元素之和,则res在原来的基础上,加上字典中该键对应的值。
- 代码一
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
res = 0
record = {}
for a in A:
for b in B:
#字典的get(key,default = None)函数返回字典中key对应的值,如果不存在该键,则返回的是传入的默认值/None
record[a+b] = record.get(a+b,0) + 1
for c in C:
for d in D:
temp = 0 - c - d
if temp in record:
res += record[temp]
return res
- 代码二
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
from collections import defaultdict
#defaultdict返回一个类似字典的对象,根据传入的参数
#defaultdict(int)创建的字典,如果字典中没有该键,函数调用int()为其提供一个默认值0
lookup = defaultdict(int)
for c in C:
for d in D:
#加法操作将计数每个键出现的次数
lookup[c+d] += 1
#要返回的结果:组数
res = 0
for a in A:
for b in B:
#组数增加
res += lookup[-(a+b)]
return res
- 代码三
复习这个题的时候,发现了代码一是可以改进的,主要是充分利用python中字典的get方法,具体代码如下:
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
res = 0
Dict = {}
for a in A:
for b in B:
Dict[a+b] = Dict.get(a+b,0) + 1
for c in C:
for d in D:
res += Dict.get(-(c+d),0)
return res