《代码随想录》学习笔记---LeetCode454:四数之和

文章介绍了如何解决寻找四个整数数组中满足特定和的元组的问题。通过避免暴力搜索的四层循环,采用哈希表存储两数之和及其出现次数,然后查找目标和的负值来优化算法,从而降低时间复杂度。

一、题目

给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/4sum-ii
 

二、具体思路

首先想到暴力搜索,从头开始依次遍历所有和的可能性,即为四层嵌套循环,时间复杂度为O(n^{4}),显然并不是一个很好的解法。

我们从之前的“两数之和”题目中获得启发,因为题目中要求的这四个数,是来自于四个不同的数组,且对具体数组下标、数字是否重复并没有要求,条件相对宽泛很多。

a+b+c+d=0

则一定有:a+b=0-(c+d)

只需要用一个hash表,记录所有a+b出现的次数:

1.key:两数之和

2.val:该和数出现的次数

然后针对 0-(c+d) 在表中进行查找,将value值累加,即可得到正确结论

代码如下:

class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
        unordered_map<int, int> map;
        int len1 = nums1.size();
        unordered_map<int, int>::iterator its;
        for (int i = 0; i < len1; i++)
        {
            for (int j = 0; j < len1; j++)
            {
                int temp = nums1[i] + nums2[j];
                its = map.find(temp);
                if (its == map.end())//couldn't find
                {
                    map.insert(make_pair(temp, 1));
                }
                else
                {
                    its->second++;
                }

            }
        }
        int cnt = 0;
        unordered_map<int, int>::iterator p;
        for (int i = 0; i < len1; i++)
        {
            for (int j = 0; j < len1; j++)
            {
                int tmp = nums3[i] + nums4[j];
                tmp = -tmp;
                p = map.find(tmp);
                if (p != map.end())cnt += p->second;
            }
        }
        return cnt;
    }
};

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值