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;
    }
};
相关推荐
小雅痞8 分钟前
[Java][Leetcode middle] 209. 长度最小的子数组
java·算法·leetcode
做时间的朋友。19 分钟前
精准核酸检测
java·数据结构·算法
冯诺依曼的锦鲤33 分钟前
从零实现高并发内存池:TCMalloc 核心架构拆解
c++·学习·算法·架构
Thomas_Lee_OR36 分钟前
多Agent路径规划 LaCAM for multi-agent path finding (MAPF)
算法·路径规划·仓储机器人·mapf
一切皆是因缘际会44 分钟前
可落地数字生命工程:从记忆厮杀到自我意识觉醒全链路,AGI内生智能硅基生命心智建模
人工智能·深度学习·算法·机器学习·ai·系统架构·agi
nlpming1 小时前
opencode Agent 详解
算法
江南十四行1 小时前
排序算法进阶:直接插入排序(简单排序)与希尔排序
数据结构·算法·排序算法
nlpming1 小时前
opencode System Prompt 构建机制 & AGENTS.md注入机制
算法
nlpming1 小时前
opencode - 安装和配置
算法
nlpming1 小时前
opencode 内置工具
算法