四数相加贰——哈希表

给你四个整数数组 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
相关推荐
小O的算法实验室4 小时前
IEEE TASE,基于MPC的多无人机协同搜索竞争群体优化方法
算法
小飞学编程...4 小时前
【哈希表】
数据结构·哈希算法·散列表
Tbisnic5 小时前
BGE-M3 算法详解:从模型架构到三种检索方式的数学原理
算法·自然语言处理·大模型·bert·transformer·注意力机制
聪明蛋子哟5 小时前
Stagehand v3多语言SDK:Python/Go/Rust/Java下的浏览器自动化统一方案
python·golang·rust
Brilliantwxx5 小时前
【算法从零到千】【55-58】哈希位图+常见数学运算 接口
算法
今天AI了吗6 小时前
Python 基础语法(一):常量、变量、输入输出与运算符
开发语言·数据库·人工智能·python·sql·深度学习·机器学习
卷无止境6 小时前
Windows 上丝滑开发 Python,并稳定构建 Docker 镜像
后端·python·docker
空堂与归6 小时前
用户分群找不到规律?用K-Means聚类算法自动发现数据模式
算法·机器学习·kmeans·聚类
TELL5216 小时前
selenium webdriver 第二次初始化的异常
开发语言·python
Csvn7 小时前
🐍 Day 4: Python 控制流 — 条件、循环与推导式的艺术
后端·python