四数相加贰——哈希表

给你四个整数数组 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
相关推荐
TonyLee017几秒前
测试数据集
python
DeepVis Research1 分钟前
【Chaos/Neuro】2026年度混沌动力学仿真与机器遗忘算法基准索引 (Benchmark Index)
人工智能·算法·数据集·混沌工程·高性能计算
啃火龙果的兔子8 分钟前
Pyglet开发游戏流程详解
python·游戏·pygame
一起养小猫16 分钟前
LeetCode100天Day9-无重复字符的最长子串与赎金信
java·开发语言·数据结构·leetcode
古城小栈16 分钟前
PyO3 库全介绍
python·rust
white-persist20 分钟前
【内网运维】Netstat与Wireshark:内网运维溯源实战解析
运维·网络·数据结构·测试工具·算法·网络安全·wireshark
会员果汁21 分钟前
7.设计模式-模板方法模式
算法·设计模式·模板方法模式
努力学算法的蒟蒻22 分钟前
day52(1.2)——leetcode面试经典150
算法·leetcode·面试
java修仙传25 分钟前
力扣hot100:字符串解码
算法·leetcode·职场和发展
技术工小李25 分钟前
2026马年年会“接福袋”游戏
python