四数相加贰——哈希表

给你四个整数数组 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
相关推荐
RSABLOCKCHAIN9 小时前
AI Agents in LangGraph-2
人工智能·python
WA内核拾荒者10 小时前
WhatsApp 账号异常检测的自动化告警系统设计
数据库·python·自动化
imuliuliang10 小时前
关于数据结构在算法设计中的核心作用解析7
算法
码流怪侠11 小时前
【GitHub】Bend:让 GPU 并行编程像写 Python 一样简单
python·github
2401_8949155312 小时前
GEO 搜索优化完整源码从零部署:环境配置、集群搭建全流程
开发语言·python·tcp/ip·算法·unity
普通网友13 小时前
共识算法实现:从工作量证明到权益证明的演进
算法·区块链·共识算法
zhiSiBuYu051713 小时前
Python3 模块开发与应用实战指南
python
ldmd28414 小时前
地图生成算法(噪声篇-Perlin,Simplex,Value noise)
算法·go·地图生成