当前位置: 首页 > article >正文

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 就可以了

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;
    }
};

更简洁的一种遍历方式

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;
    }
};

 


http://www.kler.cn/a/578045.html

相关文章:

  • flutter的debounce_throttle插件使用
  • 进程、线程、锁面试前复习(尽力局)
  • Myslq表的内外连接
  • Python项目-基于Django的在线教育平台开发
  • 【音视频】ffplay简单过滤器
  • 【算法】010、合并两个有序链表
  • 使用 display: flex 实现动态布局:每行两个 item,单数时最后一个占满整行
  • Redis数据结构——list
  • nacos和Eureka的学习
  • Core Speech Kit(基础语音服务)
  • ICRA顶会 | 当无人机遇上扩散模型:如何让四旋翼飞行器在复杂环境中「稳如泰山」?
  • 重塑用户体验:用户界面设计、交互设计及视觉体验优化的融合策略
  • 【C语言】外围电路异常排查方式
  • Python刷题:Python基础
  • 蓝桥-反倍数-oj152
  • 3.6c语言
  • 导电陶瓷粉:掺铑(Rh)钛酸钡在MLCC内电极浆料中的应用与创新-京煌科技
  • Spring Cloud Alibaba OpenFeign 实战:打造稳定高效的远程调用
  • MySql的安装及数据库的基本操作命令
  • 物联网-智慧农业中与市场需求对接的一体化解决方案