zl程序教程

您现在的位置是:首页 >  后端

当前栏目

72、【哈希表】leetcode——454. 四数相加 II(C++版本)

C++LeetCode哈希 版本 II 相加 72 四数
2023-09-11 14:20:01 时间

题目描述

在这里插入图片描述

在这里插入图片描述

原题链接:454. 四数相加 II

解题思路

本题构建Hash表的关键是确定Value的含义,因为目标是找到四个集合中各种情况为0的情况之和,因此不需要对相同情况去重,Value设置为满足某种对应情况的出现次数。当找到一次满足nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0时,就将本次情况对应的次数相加。

一、加上三个数,求另一个数

题中目标是求nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0,那么就可以让第四个数,映射为Hash表record中,根据0-(nums1[i] + nums2[j] + nums3[k])来看是否有对应的数,在record中。如果在,则说明存在对应结果,而对应结果的情况个数,应为nums4[l]对应数值出现的次数,即0-(nums1[i] + nums2[j] + nums3[k])nums4[l]中符合对应情况的个数。

因此record中的Keynums4[l]Valuenums4[l]的个数。

class Solution {
public:
    void hashRecord(unordered_map<int, int>& record, vector<int>& nums){
        for(int i = 0; i < nums.size(); i++) {
            record[nums[i]]++;  // 每出现一个对应数值,计数增加一次
        }
    }

    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
        int res = 0;

       unordered_map<int, int> record;        
       hashRecord(record, nums4);

        for(int num1 : nums1) {
            for(int num2 : nums2) {
                for(int num3: nums3) {
                    auto it = record4.find(0 - num1 - num2 - num3);                    
                    // 找到可以让四数之和为0的情况
                    if(it != record4.end()) {                            
                        res += it->second;        // 加上另外三个数会和nums4中对应的it->first为0的情况之和
                    } 
                }
            }
        }
        return res;
    }
};

时间复杂度 O ( n 3 ) O(n^3) O(n3)
空间复杂度 O ( n ) O(n) O(n)

这个情况会超时,需要对其进行优化。

二、两两求和,求两集合之和为0的情况

考虑到求两数之和题目,我们可以将四个集合中两两相合,构成两个集合之间的对比,那么这个题便变为求两集合之和为0,就将时间复杂度从 O ( n 3 ) O(n^3) O(n3)降为了 O ( n 2 ) O(n^2) O(n2)

nums1[i] + nums2[j]构成一个集合,映射成一个Hash表,Keynums1[i]+nums2[j]Value为该值出现的次数。

nums3[k] + nums4[l]构成另一个集合。符合目标条件的值,变为集合中数值等于0-(nums1[i]+nums2[j])的值。每找到一次满足该值情况,就将集合1中符合该情况的次数相加。

class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
        int res = 0;
        unordered_map<int, int> record;        

        for(int num1 : nums1) {         // 求nums1[i] + nums[j]之和的集合
            for(int num2 : nums2) {
                record[num1 + num2]++;  // 求相加后等于某一值出现的次数
            }
        }

        for(int num3 : nums3) {
            for(int num4 : nums4) {
                int gap = 0-(num3 + num4);  // 找满足nums1[i]+nums2[j]+nums3[k]+nums4[l]=0的情况
                if(record.find(gap) != record.end()) {
                    res += record[gap];     // 对应满足情况次数相加
                }
            }
        }

        return res;

    }
};

时间复杂度为 O ( n 2 ) O(n^2) O(n2)
空间复杂度为 O ( n ) O(n) O(n)

参考文章:第454题.四数相加II