python 力扣454四数相加 II

本文介绍如何使用Python的collections.Counter高效地计算四个整数数组中两两和等于目标值的组合数量。通过Counter实现计数功能,简化了传统O(n^2)的时间复杂度,提高了代码效率。
摘要由CSDN通过智能技术生成

原题链接

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})
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值