四数相加贰——哈希表

给你四个整数数组 nums1nums2nums3nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:

  • 0 <= i, j, k, l < n
  • nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0

示例 1:

复制代码
输入:nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
输出:2
解释:
两个元组如下:
1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0

思路

用哈希表记录 nums1+nums2 的所有两数之和出现次数,再遍历 nums3+nums4 查找是否存在能与之凑成 0 的相反数,从而快速统计四数和为 0 的组合数量。

python 复制代码
from collections import defaultdict
from typing import List


class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        d=defaultdict(int)
        res=0
        for n1 in nums1:
            for n2 in nums2:
                d[n1+n2]+=1

        for n3 in nums3:
            for n4 in nums4:
                res+=d[-(n3+n4)]
        return res
相关推荐
鸽芷咕1 天前
为什么越来越多开发者转向 CANN 仓库中的 Python 自动化方案?
python·microsoft·自动化·cann
秋邱1 天前
用 Python 写出 C++ 的性能?用CANN中PyPTO 算子开发硬核上手指南
开发语言·c++·python
野犬寒鸦1 天前
从零起步学习并发编程 || 第六章:ReentrantLock与synchronized 的辨析及运用
java·服务器·数据库·后端·学习·算法
霖霖总总1 天前
[小技巧66]当自增主键耗尽:MySQL 主键溢出问题深度解析与雪花算法替代方案
mysql·算法
rainbow68891 天前
深入解析C++STL:map与set底层奥秘
java·数据结构·算法
wazmlp0018873691 天前
python第三次作业
开发语言·python
wangjialelele1 天前
平衡二叉搜索树:AVL树和红黑树
java·c语言·开发语言·数据结构·c++·算法·深度优先
深蓝电商API1 天前
住宅代理与数据中心代理在爬虫中的选择
爬虫·python
xuxie991 天前
day 21 双向链表以及循环链表
数据结构·链表
驱动探索者1 天前
linux mailbox 学习
linux·学习·算法