leetcode454. 四数相加 II

leetcode454. 四数相加 II,第1张

一:题目

二:上码


class Solution {
public:

    /**
        思路:本题我们是先处理前两个数组,求出两个数组中任意两个元素之和,然后用map容器进行存储,
             并记录个数,然后调用find()函数,跟后两个数组中的任意两个元素相加,做差处理,
             那么的话,如果等于0,就统计其  value值 (比如 key = 4,那么可能是 1 +3 或者
             2 + 2, 这样的话 如果后两个数组有{2,2}的话 那么我们就有两种可能性)    

    */
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
        unordered_map<int,int> m;


        for (int a:nums1) {
            for (int b:nums2) {
                m[a+b]++;
            }
        }

        int ans = 0;

        for (int c : nums3) {
           for (int d: nums4) {

                auto mt = m.find(-(c+d));// 因为我们想求的是和为0,那么我们就要寻找num3,nums4中
                                        // -(c+d) = a + b 
                if(mt != m.end()) {     //这个mt指针指向的就是 我们当前 (-(c+d))所对应的 [key,value]值
                    ans += mt->second; 
                }
           } 
        }

        return ans;
    }
};

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/713579.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-24
下一篇 2022-04-24

发表评论

登录后才能评论

评论列表(0条)

保存