Leetcode454. 四数相加 II

这篇博客探讨了一种优化算法,用于计算四个整数数组A、B、C和D中,任意两对元素相加等于零的组合数量。原始方法使用两个映射记录相加结果,而改进后的实现则在遍历C和D数组时直接查找目标值,减少了迭代次数,提高了效率。这种方法类似于两数之和问题的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最初的想法:用两个map来记录相加结果

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        unordered_map<int, int> m;
        unordered_map<int, int> n;
        for(int a : A){
            for(int b : B){
                m[a + b]++;
            }
        }

        for(int c : C){
            for(int d : D){
                n[c + d]++;
            }
        }      

        int cnt = 0;

        for(auto &item : m){
            if(n.find(0-item.first) != n.end()){
                cnt += n[0-item.first] * item.second;
            }
        }
        return cnt;
    }
};

改进写法:在第二个大循环里就可以进行判断了。

遍历大C和大D数组时,找到如果 0-(c+d) 在map中出现过的话,就用count把map中key对应的value也就是出现次数统计出来。其思想和两数之和差不多。

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        unordered_map<int, int> m;
        for(int a : A){
            for(int b : B){
                m[a + b]++;
            }
        }

        int cnt = 0;

        for(int c : C){
            for(int d : D){
                if(m.find(0 - c - d) != m.end()){
                    cnt += m[0 - c - d];
                }
            }
        }
        return cnt;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值