leetcode454 四数相加

四数相加Ⅱ的解法可以将四数分为两组,即"分组 + 哈希":

  • 初始化哈希表。

  • 分组:nums1 和 nums2 一组,nums3 和 nums4 一组。

  • 分别对 nums1 和 nums2 进行遍历,将所有 nums1 和 nums2 的值的和作为哈希表的 key,和的次数作为哈希表的 value。

  • 分别对 nums3 和 nums4 进行遍历,若 -(nums3[k] + nums4[l]) 在哈希表中,则四元组次数 +hash[-(nums3[k]+nums4[l])] 次。

或者说:

  1. 首先定义 一个unordered_map,key放a和b两数之和,value 放a和b两数之和出现的次数。
  2. 遍历大A和大B数组,统计两个数组元素之和,和出现的次数,放到map中。
  3. 定义int变量count,用来统计 a+b+c+d = 0 出现的次数。
  4. 再遍历大C和大D数组,找到如果 0-(c+d) 在map中出现过的话,就用count把map中key对应的value也就是出现次数统计出来。
  5. 最后返回统计值 count 就可以了
cpp 复制代码
class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
        unordered_map<int, int> hash;
        int count = 0;
        for(int i = 0; i < nums1.size(); i++){
            for(int j = 0; j < nums2.size(); j++){
                hash[nums1[i] + nums2[j]]++;
            }
        }
        for(int i = 0; i < nums3.size(); i++){
            for(int j = 0; j < nums2.size(); j++){
                if(hash.find(-(nums3[i]+nums4[j])) != hash.end()){
                    count += hash[-(nums3[i]+nums4[j])];
                }
            }
        }
        return count;
    }
};

更简洁的一种遍历方式

cpp 复制代码
class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
        unordered_map<int, int> hash;
        int count = 0;
        for(int a: nums1){
            for(int b: nums2){
                hash[a + b]++;
            }
        }
        for(int c: nums3){
            for(int d: nums4){
                if(hash.find(-(c + d)) != hash.end()){
                    count += hash[-(c + d)];
                }
            }
        }
        return count;
    }
};
相关推荐
重庆小透明13 分钟前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
desssq33 分钟前
力扣:70. 爬楼梯
算法·leetcode·职场和发展
clock的时钟1 小时前
暑期数据结构第一天
数据结构·算法
小小小小王王王1 小时前
求猪肉价格最大值
数据结构·c++·算法
岁忧2 小时前
(LeetCode 面试经典 150 题 ) 58. 最后一个单词的长度 (字符串)
java·c++·算法·leetcode·面试·go
BIYing_Aurora2 小时前
【IPMV】图像处理与机器视觉:Lec13 Robust Estimation with RANSAC
图像处理·人工智能·算法·计算机视觉
martian6654 小时前
支持向量机(SVM)深度解析:从数学根基到工程实践
算法·机器学习·支持向量机
孟大本事要学习4 小时前
算法19天|回溯算法:理论基础、组合、组合总和Ⅲ、电话号码的字母组合
算法
??tobenewyorker4 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
让我们一起加油好吗4 小时前
【基础算法】贪心 (二) :推公式
数据结构·数学·算法·贪心算法·洛谷