LeetCode--454.四数相加 II(哈希表)

题目描述

给你四个整数数组 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

提示:

复制代码
n == nums1.length
n == nums2.length
n == nums3.length
n == nums4.length
1 <= n <= 200
-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228

代码

java 复制代码
class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        // 新建map,以 sum为key, count为value
        Map<Integer, Integer> map = new HashMap<>();
        // 初始化返回结果
        int result = 0;
        // 遍历nums1和nums2求和
        for(int i : nums1){
            for(int j : nums2){
                int sum = i + j;
                // 若不存在value会返回默认值0
                int count = map.getOrDefault(sum, 0) + 1;
                map.put(sum, count);
            }
        }

        // 遍历nums3和nums4求和
        for(int i : nums3){
            for(int j : nums4){
                int sum = i + j;
                // 找是否在map中有相反数,若不存在则返回0
                int count = map.getOrDefault(0-sum, 0);
                result += count;
            }
        }

        return result;

    }
}
相关推荐
漫随流水2 小时前
c++编程:D进制的A+B(1022-PAT乙级)
数据结构·c++·算法
tankeven2 小时前
HJ159 没挡住洪水
c++·算法
美式请加冰2 小时前
斐波那契数列介绍和使用
算法
paeamecium2 小时前
【PAT】 - Course List for Student (25)
数据结构·c++·算法·pat考试
wen__xvn2 小时前
力扣洛谷模拟题刷题2
算法·leetcode·职场和发展
漫随流水3 小时前
c++编程:说反话(1009-PAT乙级)
数据结构·c++·算法
计算机安禾3 小时前
【数据结构与算法】第23篇:树、森林与二叉树的转换
c语言·开发语言·数据结构·c++·线性代数·算法·矩阵
温九味闻醉3 小时前
人工智能应用作业1:PPO强化学习算法
人工智能·算法
wfbcg4 小时前
每日算法练习:LeetCode 167. 两数之和 II - 输入有序数组 ✅
算法·leetcode·职场和发展