454. 四数相加 II

题目描述

给你四个整数数组 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

示例 2:

复制代码
输入:nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
输出:1

提示:

  • n == nums1.length
  • n == nums2.length
  • n == nums3.length
  • n == nums4.length
  • 1 <= n <= 200
  • -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228

解答

cpp 复制代码
class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
        // 哈希表法
        // key 为 a + b的数值,value 为a+b 出现 的次数

        unordered_map<int, int> umap;
        for(int a : nums1)
        {
            for(int b : nums2)
            {
                umap[a + b]++;
            }
        }

        int count = 0; // 统计 a + b + c + d  == 0 的情况数量
        // 即在umap查找 a+b == -c-d的kv对
        for(int c : nums3)
        {
            for(int d : nums4)
            {
                if(umap.find(-( c + d)) != umap.end())
                {
                    count += umap[-( c + d)];
                }
            }
        }
        return count;
    }
};
相关推荐
.30-06Springfield11 分钟前
决策树(Decision tree)算法详解(ID3、C4.5、CART)
人工智能·python·算法·决策树·机器学习
我不是哆啦A梦11 分钟前
破解风电运维“百模大战”困局,机械版ChatGPT诞生?
运维·人工智能·python·算法·chatgpt
xiaolang_8616_wjl16 分钟前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
small_wh1te_coder22 分钟前
硬件嵌入式学习路线大总结(一):C语言与linux。内功心法——从入门到精通,彻底打通你的任督二脉!
linux·c语言·汇编·嵌入式硬件·算法·c
hqxstudying1 小时前
Java创建型模式---单例模式
java·数据结构·设计模式·代码规范
挺菜的1 小时前
【算法刷题记录(简单题)002】字符串字符匹配(java代码实现)
java·开发语言·算法
sun0077001 小时前
数据结构——栈的讲解(超详细)
数据结构
凌肖战4 小时前
力扣网编程55题:跳跃游戏之逆向思维
算法·leetcode
88号技师5 小时前
2025年6月一区-田忌赛马优化算法Tianji’s horse racing optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
ゞ 正在缓冲99%…6 小时前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划