四数相加贰——哈希表

给你四个整数数组 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
相关推荐
一个不知名程序员www1 小时前
算法学习入门 --- 哈希表和unordered_map、unordered_set(C++)
c++·算法
jaray1 小时前
PyCharm 2024.3.2 Professional 如何更换 PyPI 镜像源
ide·python·pycharm·pypi 镜像源
Psycho_MrZhang1 小时前
Neo4j Python SDK手册
开发语言·python·neo4j
Sarvartha2 小时前
C++ STL 栈的便捷使用
c++·算法
web3.08889992 小时前
1688图片搜索API,相似商品精准推荐
开发语言·python
少云清2 小时前
【性能测试】15_JMeter _JMeter插件安装使用
开发语言·python·jmeter
夏鹏今天学习了吗2 小时前
【LeetCode热题100(92/100)】多数元素
算法·leetcode·职场和发展
光羽隹衡2 小时前
机器学习——TF-IDF实战(红楼梦数据处理)
python·tf-idf
飞Link3 小时前
深度解析 MSER 最大稳定极值区域算法
人工智能·opencv·算法·计算机视觉
bubiyoushang8883 小时前
基于CLEAN算法的杂波抑制Matlab仿真实现
数据结构·算法·matlab