leetcode454 四数相加

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

  • 初始化哈希表。

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

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

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

或者说:

  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;
    }
};
相关推荐
ZhengEnCi9 小时前
GPT-6 Astra 爆改 Qwen 权重真有那么神吗:权重空间编程 0.016% 参数的真相
算法·架构
罗西的思考9 小时前
【轻量化复刻大模型 / KIMI K3】KDA(Kimi Delta Attention):并行
人工智能·算法·机器学习
夜不会漫长11 小时前
C++:红黑树
数据结构·算法
AI备案指南-满满12 小时前
算法备案审核不通过,一般是什么原因?
java·人工智能·算法·大模型备案·算法备案·大模型登记
Ramble_Naylor12 小时前
Rust深度解读:Send 与 Sync 的本质与线程安全边界
python·算法·rust
秋天的怀念_David12 小时前
算法一千零一夜 · 第二十三夜 电力民生写成的曲线
java·程序人生·算法
不一样的故事12612 小时前
NB/T 47013.8-2015 附录D 吸枪技术
人工智能·经验分享·算法
通问AI12 小时前
用 200 行 Python 给文档库做「上下文完整度」自检:四个可复算的检查项
算法
揽星河..13 小时前
【C语言】扫雷游戏
c语言·算法·游戏