LeetCode 454. 四数相加 II(C++)

思路:
如果采用直接排列组合,时间复杂度很高O(n4);通过分治法,四个数相加就等于两组数相加并判断,以此提高效率,时间复杂度O(n2)。

1.题目如下:

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

示例 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

2.代码如下:

class Solution {
public:
// 思路一:暴力回溯:O(n4)  超时

// 思路二:分治思路,将数组分为两组,分别进行遍历 O(n2)
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
        int n=nums1.size();
        unordered_map<int,int> mapTemp1;
        unordered_map<int,int> mapTemp2;
        //第一组的数之和
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                mapTemp1[nums1[i]+nums2[j]]++;
            }
        }
        //第二组的数之和
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                mapTemp2[nums3[i]+nums4[j]]++;
            }
        }
        int sum=0;
        //再遍历两个哈希表,当x.first和y.first*-1相等代表和为0
        //由于答案要求的是元素标记的组数,而非元素组合数,所以不会有重复组合的情况
        for(auto x:mapTemp1){
            for(auto y:mapTemp2){
                if(x.first == y.first*(-1)){
                    sum+=x.second*y.second;
                }
            }
        }
        return sum;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_panbk_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值