class Solution:
def fourSumCount(self, A, B, C, D) -> int:
dict={}
for i in A:#遍历大A和大B数组,统计两个数组元素之和,和出现的次数,放到dict中
for j in B:
if i+j in dict:
dict[i+j]+=1
else:
dict[i+j]=1
count=0
for m in C:#遍历大C和大D数组,找到如果 0-(c+d) 在dict中出现过的话,就用count把map中key对应的value也就是出现次数统计出来
for n in D:
if (0-m-n) in dict:
count+=dict[0-m-n]
return count
test=Solution()
print(test.fourSumCount(A = [ 1, 2],B = [-2,-1],C = [-1, 2],D = [ 0, 2]))
时间复杂度: O(n^2)空间复杂度: O(n)
使用容器
import collections
class Solution:
def fourSumCount(self, A, B, C, D) -> int:
dict=collections.Counter()#Counter提供了可哈希对象的计数功能
for i in A:
for j in B:
dict[i+j]+=1
count=0
for m in C:
for n in D:
if (0-m-n) in dict:
count+=dict[0-m-n]
return count
test=Solution()
print(test.fourSumCount(A = [ 1, 2],B = [-2,-1],C = [-1, 2],D = [ 0, 2]))
Collections.Counter 用法
官方文档链接
参考博客
Collection模块
这个模块实现了特定目标的容器,以提供Python标准内建容器 dict、list、set、tuple 的替代选择
(1)Counter:字典的子类,提供了可哈希对象的计数功能
(2)defaultdict:字典的子类,提供了一个工厂函数,为字典查询提供了默认值
(3)OrderedDict:字典的子类,保留了他们被添加的顺序
(4)namedtuple:创建命名元组子类的工厂函数
(5)deque:类似列表容器,实现了在两端快速添加(append)和弹出(pop)
(6)ChainMap:类似字典的容器类,将多个映射集合到一个视图里面
Counter
Counter是一个dict子类,主要是用来对你访问的对象的频率进行计数。
常用方法:
elements():返回一个迭代器,每个元素重复计算的个数,如果一个元素的计数小于1,就会被忽略。
most_common([n]):返回一个列表,提供n个访问频率最高的元素和计数
subtract([iterable-or-mapping]):从迭代对象中减去元素,输入输出可以是0或者负数
update([iterable-or-mapping]):从迭代对象计数元素或者从另一个 映射对象 (或计数器) 添加。
# 统计字符出现的次数
>>> import collections
>>> collections.Counter('hello world')
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
# 统计单词数
>>> collections.Counter('hello world hello world hello nihao'.split())
Counter({'hello': 3, 'world': 2, 'nihao': 1})