leetcode 454. 4sum-ii 四数相加 II python3

时间:2020-9-13

题目地址:https://leetcode-cn.com/problems/4sum-ii/

题目难度:Medium

题目描述:

给定四个包含整数的数组列表 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


思路1:还想用组合,但是超时了,题解里有求两两数组之和的,还是得用哈希,这是用的collections.Counter

代码段1:通过

class Solution:
    def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
        a_add_b = collections.Counter(a + b for a in A for b in B)
        print(a_add_b)
        return sum(a_add_b.get(- c - d, 0) for c in C for d in D)

总结:

  1. 对应位置相加 a_add_b = [a + b for a, b in zip(A, B)] ,组合相加 a_add_b = [a + b for a in A for b in B]


思路2:defaultdict

代码段2:通过

class Solution:
    def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
        a_add_b = collections.defaultdict(int)
        res = 0
        for a in A:
            for b in B:
                a_add_b[a+b] += 1
        
        for c in C:
            for d in D:
                res += a_add_b[- c - d]
        
        return res

总结:

  1. 感觉自己对于数据结构还是掌握的不太清楚,有点混乱,还是得多练习,最近总想转java,算了,脑子不够,还是把python学到极致吧,加油

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值