每日一题 | 454.四数相加 II

每日一题 | 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

思路

这道题目采用哈希表来解题,这里让我们浅浅的复习一下哈希表的基础知识。

哈希表

哈希表(Hash Table,也有一些书籍称为“散列表”)

哈希表是根据关键的值直接访问的数据结构。

我们经常用的数组就是一张哈希表,哈希表的关键码就是数组索引下标,通过下标直接访问数组中的元素。

解题流程

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

  • 初始化哈希表。
  • 分组:nums1 和 nums2 一组,nums3 和 nums4 一组。
  • 分别对 nums1 和 nums2 进行遍历,将所有 nums1 和 nums2 的值的和作为哈希表的 key,和的次数作为哈希表的 value。
  • 分别对 nums3 和 nums4 进行遍历,若 -(nums1[k] + nums4[l]) 在哈希表中,则四元组次数 +hash[-(nums3[k]+nums4[l])] 次。

代码展示

Python3

class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:

        # 初始化哈希表
        hash = {}
        cnt = 0

        # 首先存储前两个数组之和
        for n1 in nums1:
            for n2 in nums2:
                # 如果在哈希表中,则对应哈希值 +1
                if n1 + n2 in hash:
                    hash[n1 + n2] += 1
                # 如果不在哈希表中,放入哈希表
                else:
                    hash[n1 + n2] = 1
        # 统计剩余两个数组的和,在哈希表中找是否存在相加为 0 的情况。
        for n3 in nums3:
            for n4 in nums4:
                if -(n3 + n4) in hash:
                    cnt += hash[-(n3 + n4)]

        return cnt

Java

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Map<Integer, Integer> map = new HashMap<>();
        int temp;
        int res = 0;
        //统计两个数组中的元素之和,同时统计出现的次数,放入map
        for (int i : nums1) {
            for (int j : nums2) {
                temp = i + j;
                if (map.containsKey(temp)) {
                    map.put(temp, map.get(temp) + 1);
                } else {
                    map.put(temp, 1);
                }
            }
        }
        //统计剩余的两个元素的和,在map中找是否存在相加为0的情况,同时记录次数
        for (int i : nums3) {
            for (int j : nums4) {
                temp = i + j;
                if (map.containsKey(0 - temp)) {
                    res += map.get(0 - temp);
                }
            }
        }
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

武师叔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值