【LeetCode454. 四数相加 II】——map型哈希表

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

思考:

本题乍一看十分复杂,其实只要运用map这种哈希类型能够很容易求解。

map型哈希表的难点就在于确定key值和value值,而在本题,我们可以将四个数组两两分组,这样我们需要存储的其实就是两个数组中两数之和,以及该两数和出现的次数。

map型哈希表:

这道题我们选择使用unordered_map这种类型的哈希表,设置int型变量count存储相加等于0的次数。

首先通过两层for循环,遍历nums1、nums2中所有的两两组合,计算它们的和并存储在哈希表中。

接着我们只需要用同样的方式遍历nums3、nums4这两个数组,依然两两组合,并求和,接着用判断语句检索哈希表中是否存在对于的值,能与之相加为0即可。

完整代码:

#include<iostream>
#include<vector>
#include<unordered_map>

using namespace std;

class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {

        unordered_map<int, int> um;
        int count = 0;//相加等于0出现的次数

        //利用两层for循环,检索nums1、nums2中所有组合,存储在um容器中
        for (int a : nums1) {
            for (int b : nums2) {
                um[a + b]++;
            }
        }

        //利用两层for循环,检索nums3、nums4中所有组合,更新count
        for (int a : nums3) {
            for (int b : nums4) {
                if (um[0 - (a + b)] > 0)
                {
                    count += um[0 - (a + b)];
                }
            }
        }
        return count;
    }
};

参考:

代码随想录


往期回顾:
LeetCode1. 两数之和
LeetCode202. 快乐数
LeetCode350. 两个数组的交集 II
LeetCode349. 两个数组的交集
LeetCode1002. 查找共用字符

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值