454. 四数相加 II

题目链接:四数相加 ||
在这里插入图片描述

思路:首先如果我们采用暴力解决的话就是 O(n^4)
的时间复杂度,所以尽可能的减小时间复杂度,通过分成两组进行遍历,比如nums1和nums2进行两层for循环相加并把结果用map进行存储,接着同样将 nums3 和 nums4 进行for循环相加,然后判断map当中是否存在有 两个数之和的相反数。通过拆成两组循环的话这样的时间复杂度就可以降低到 O(n^2)
C++代码:

class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
        if(nums1.size() == 0 || nums2.size() == 0 || nums3.size() == 0 || nums4.size() == 0) return 0;
        unordered_map<int, int> map;
        int count = 0;
        for(int num1 : nums1){
            for(int num2 : nums2){
                map[num1 + num2]++;
            }
        }
        for(int num3 : nums3){
            for(int num4 : nums4){
                count += map[-(num3 + num4)];
            }
        }
        return count;
    }
};

JavaScript代码:

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @param {number[]} nums3
 * @param {number[]} nums4
 * @return {number}
 */
var fourSumCount = function(nums1, nums2, nums3, nums4) {
    if(nums1 == null || nums2 == null || nums3 == null || nums4 == null || nums1.length == 0 || nums2.length == 0 || nums3.length == 0 || nums4.length == 0) return 0;
    let map = new Map(), cnt = 0;
    for(let i = 0; i < nums1.length; i++){
        for(let j = 0; j < nums2.length; j++){
            let bool = map.get(nums1[i] + nums2[j]);
            if(bool){
                map.set(nums1[i] + nums2[j], bool + 1);
            }else{
                map.set(nums1[i] + nums2[j], 1);
            }
        }
    }
    for(let i = 0; i < nums3.length; i++){
        for(let j = 0; j < nums4.length; j++){
            let bool = map.get(-(nums3[i] + nums4[j]));
            if(bool){
                cnt += bool;
            }
        }
    }
    return cnt;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值