LeetCode 题解工作台

数组中不等三元组的数目

给你一个下标从 0 开始的正整数数组 nums 。请你找出并统计满足下述条件的三元组 (i, j, k) 的数目: 0 nums[i] 、 nums[j] 和 nums[k] 两两不同 。 换句话说: nums[i] != nums[j] 、 nums[i] != nums[k] 且 nums[j]…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们可以直接枚举所有的三元组 $(i, j, k)$,统计所有符合条件的数量。 时间复杂度 ,其中 为数组 的长度。空间复杂度 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的正整数数组 nums 。请你找出并统计满足下述条件的三元组 (i, j, k) 的数目:

  • 0 <= i < j < k < nums.length
  • nums[i]nums[j]nums[k] 两两不同
    • 换句话说:nums[i] != nums[j]nums[i] != nums[k]nums[j] != nums[k]

返回满足上述条件三元组的数目

 

示例 1:

输入:nums = [4,4,2,4,3]
输出:3
解释:下面列出的三元组均满足题目条件:
- (0, 2, 4) 因为 4 != 2 != 3
- (1, 2, 4) 因为 4 != 2 != 3
- (2, 3, 4) 因为 2 != 4 != 3
共计 3 个三元组,返回 3 。
注意 (2, 0, 4) 不是有效的三元组,因为 2 > 0 。

示例 2:

输入:nums = [1,1,1,1,1]
输出:0
解释:不存在满足条件的三元组,所以返回 0 。

 

提示:

  • 3 <= nums.length <= 100
  • 1 <= nums[i] <= 1000
lightbulb

解题思路

方法一:暴力枚举

我们可以直接枚举所有的三元组 (i,j,k)(i, j, k),统计所有符合条件的数量。

时间复杂度 O(n3)O(n^3),其中 nn 为数组 numsnums 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def unequalTriplets(self, nums: List[int]) -> int:
        n = len(nums)
        ans = 0
        for i in range(n):
            for j in range(i + 1, n):
                for k in range(j + 1, n):
                    ans += (
                        nums[i] != nums[j] and nums[j] != nums[k] and nums[i] != nums[k]
                    )
        return ans
speed

复杂度分析

指标
时间complexity ranges from O(n^3) for brute force to O(n^2) with hash-based optimizations due to the nested loops. Space complexity is O(n) for frequency maps and auxiliary counters.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if candidate triplets maintain array order and are distinct.

  • question_mark

    Notice that constraints are small enough to allow nested loops.

  • question_mark

    Consider hash map usage to avoid repeated comparisons.

warning

常见陷阱

外企场景
  • error

    Counting triplets that repeat numbers or ignore order.

  • error

    Mismanaging hash counts leading to overcounting.

  • error

    Assuming all three numbers are unique globally rather than per triplet.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count triplets with at least two distinct numbers instead of all distinct.

  • arrow_right_alt

    Find unequal quadruplets using a similar scanning plus hash approach.

  • arrow_right_alt

    Compute the sum of all distinct triplets instead of just counting them.

help

常见问题

外企场景

数组中不等三元组的数目题解:数组·哈希·扫描 | LeetCode #2475 简单