LeetCode 题解工作台

四数相加 II

给你四个整数数组 nums1 、 nums2 、 nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足: 0 nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0 示例 1: 输入: nums1 = [1,2…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

我们可以将数组 和 中的元素 和 相加,将所有可能的和存储在哈希表 中,其中键为两数之和,值为两数之和出现的次数。 然后我们遍历数组 和 中的元素 和 ,令 为目标值,那么答案即为 的累加和。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你四个整数数组 nums1nums2nums3nums4 ,数组长度都是 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
lightbulb

解题思路

方法一:哈希表

我们可以将数组 nums1nums1nums2nums2 中的元素 aabb 相加,将所有可能的和存储在哈希表 cntcnt 中,其中键为两数之和,值为两数之和出现的次数。

然后我们遍历数组 nums3nums3nums4nums4 中的元素 ccdd,令 c+dc+d 为目标值,那么答案即为 cnt[(c+d)]cnt[-(c+d)] 的累加和。

时间复杂度 O(n2)O(n^2),空间复杂度 O(n2)O(n^2),其中 nn 是数组的长度。

1
2
3
4
5
6
7
class Solution:
    def fourSumCount(
        self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]
    ) -> int:
        cnt = Counter(a + b for a in nums1 for b in nums2)
        return sum(cnt[-(c + d)] for c in nums3 for d in nums4)
speed

复杂度分析

指标
时间complexity is O(n^2) for computing pair sums and lookups, instead of O(n^4). Space complexity is O(n^2) to store hash map frequencies of the first two arrays' sums.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Mentions using pair sums to reduce brute-force iterations.

  • question_mark

    Checks if candidates from remaining arrays complement existing sums.

  • question_mark

    Looks for efficient O(n^2) approach instead of O(n^4).

warning

常见陷阱

外企场景
  • error

    Forgetting negative values when computing complements leads to wrong counts.

  • error

    Double-counting pairs by not using hash map frequencies correctly.

  • error

    Attempting a naive four-loop approach causing TLE for larger n.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Three-sum or k-sum problems with similar pair-sum hash patterns.

  • arrow_right_alt

    Finding tuples with product equal to a target instead of sum.

  • arrow_right_alt

    Using sorted arrays with two-pointer approaches instead of hash maps.

help

常见问题

外企场景

四数相加 II题解:数组·哈希·扫描 | LeetCode #454 中等