LeetCode 题解工作台

统计特殊四元组

给你一个 下标从 0 开始 的整数数组 nums ,返回满足下述条件的 不同 四元组 (a, b, c, d) 的 数目 : nums[a] + nums[b] + nums[c] == nums[d] ,且 a 示例 1: 输入: nums = [1,2,3,6] 输出: 1 解释: 满足要求的唯…

category

3

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

class Solution: def countQuadruplets(self, nums: List[int]) -> int:

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 下标从 0 开始 的整数数组 nums ,返回满足下述条件的 不同 四元组 (a, b, c, d)数目

  • nums[a] + nums[b] + nums[c] == nums[d] ,且
  • a < b < c < d

 

示例 1:

输入:nums = [1,2,3,6]
输出:1
解释:满足要求的唯一一个四元组是 (0, 1, 2, 3) 因为 1 + 2 + 3 == 6 。

示例 2:

输入:nums = [3,3,6,4,5]
输出:0
解释:[3,3,6,4,5] 中不存在满足要求的四元组。

示例 3:

输入:nums = [1,1,1,3,5]
输出:4
解释:满足要求的 4 个四元组如下:
- (0, 1, 2, 3): 1 + 1 + 1 == 3
- (0, 1, 3, 4): 1 + 1 + 3 == 5
- (0, 2, 3, 4): 1 + 1 + 3 == 5
- (1, 2, 3, 4): 1 + 1 + 3 == 5

 

提示:

  • 4 <= nums.length <= 50
  • 1 <= nums[i] <= 100
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def countQuadruplets(self, nums: List[int]) -> int:
        ans, n = 0, len(nums)
        for a in range(n - 3):
            for b in range(a + 1, n - 2):
                for c in range(b + 1, n - 1):
                    for d in range(c + 1, n):
                        if nums[a] + nums[b] + nums[c] == nums[d]:
                            ans += 1
        return ans
speed

复杂度分析

指标
时间complexity ranges from O(n^3) with hash optimization to O(n^4) for pure brute force. Space complexity is O(n) for hash map storage. Small array size allows these approaches to run efficiently.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect questions on handling duplicate numbers in quadruplets.

  • question_mark

    They may probe if you can reduce four nested loops using a hash table.

  • question_mark

    Look for awareness of early pruning opportunities to speed up array scans.

warning

常见陷阱

外企场景
  • error

    Counting quadruplets incorrectly when indices are not strictly increasing.

  • error

    Failing to use hash lookup and iterating unnecessarily over d multiple times.

  • error

    Overlooking array length constraints and optimizing prematurely for larger n.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count quadruplets where nums[a] * nums[b] * nums[c] equals nums[d].

  • arrow_right_alt

    Find quadruplets with any sum equal to a target value instead of the fourth element.

  • arrow_right_alt

    Return indices of quadruplets instead of just counting them.

help

常见问题

外企场景

统计特殊四元组题解:数组·哈希·扫描 | LeetCode #1995 简单