0
点赞
收藏
分享

微信扫一扫

454. 四数相加 II(哈希表)(Leetcode刷题笔记)

山竹山竹px 2022-02-05 阅读 169

454. 四数相加 II(哈希表)(Leetcode刷题笔记)

https://lunan0320.cn

文章目录

题目

给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:

0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0

示例 1:

输入:nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
输出:2
解释:
两个元组如下:

  1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
  2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0

示例 2:

输入:nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
输出:1

解题代码 C++(哈希表)

class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
        //因为是4个数组,因此,两两组合。
        //哈希表的键是前两个数组中元素的和a+b,值是a+b出现的次数
        unordered_map<int,int> hash_map;
        //count表示满足的个数
        int count = 0;
        //遍历前两个数组,构建哈希表
        for(int a : nums1){
            for(int b : nums2){
                hash_map[a+b]++;
            }
        }
        //遍历后两个数组,找到满足条件的
        for(int c : nums3){
            for(int d : nums4){
                //找到满足情况的组合,其中count不是加1,因为满足a+b的可能有多个
                //使用hash_map.find()和hash_map.count()函数均可
                //if(hash_map.find(-(c+d)) != hash_map.end()) count += hash_map[-(c+d)];
                if(hash_map.count(-(c+d))) count += hash_map[-(c+d)];
            }
        }
        return count;
    }
};

算法效率

举报

相关推荐

0 条评论