LeetCode 题解工作台
统计好三元组
给你一个整数数组 arr ,以及 a 、 b 、 c 三个整数。请你统计其中好三元组的数量。 如果三元组 (arr[i], arr[j], arr[k]) 满足下列全部条件,则认为它是一个 好三元组 。 0 |arr[i] - arr[j]| |arr[j] - arr[k]| |arr[i] - …
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·结合·enumeration
答案摘要
我们可以枚举所有的 , 和 ,其中 $i \lt j \lt k$,判断是否同时满足 $|\textit{arr}[i] - \textit{arr}[j]| \le a|\textit{arr}[j] - \textit{arr}[k]| \le b$ 和 $|\textit{arr}[i] - \textit{arr}[k]| \le c$,如果满足则将答案加一。 枚举结束后,即可得到答案。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·enumeration 题型思路
题目描述
给你一个整数数组 arr ,以及 a、b 、c 三个整数。请你统计其中好三元组的数量。
如果三元组 (arr[i], arr[j], arr[k]) 满足下列全部条件,则认为它是一个 好三元组 。
0 <= i < j < k < arr.length|arr[i] - arr[j]| <= a|arr[j] - arr[k]| <= b|arr[i] - arr[k]| <= c
其中 |x| 表示 x 的绝对值。
返回 好三元组的数量 。
示例 1:
输入:arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3 输出:4 解释:一共有 4 个好三元组:[(3,0,1), (3,0,1), (3,1,1), (0,1,1)] 。
示例 2:
输入:arr = [1,1,2,2,3], a = 0, b = 0, c = 1 输出:0 解释:不存在满足所有条件的三元组。
提示:
3 <= arr.length <= 1000 <= arr[i] <= 10000 <= a, b, c <= 1000
解题思路
方法一:枚举
我们可以枚举所有的 , 和 ,其中 ,判断是否同时满足 , 和 ,如果满足则将答案加一。
枚举结束后,即可得到答案。
时间复杂度 ,其中 为数组 的长度。空间复杂度 。
class Solution:
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
ans, n = 0, len(arr)
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
ans += (
abs(arr[i] - arr[j]) <= a
and abs(arr[j] - arr[k]) <= b
and abs(arr[i] - arr[k]) <= c
)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n^3) in naive enumeration, but early breaks can reduce checks to roughly O(n^2) for most inputs. Space complexity is O(1) aside from storing input, as no additional structures are required. |
| 空间 | O(S) |
面试官常问的追问
外企场景- question_mark
Asks if brute-force enumeration is acceptable given small constraints.
- question_mark
Checks understanding of absolute difference and triplet conditions.
- question_mark
Watches for correct index ordering to prevent miscounting.
常见陷阱
外企场景- error
Using <= instead of < for indices, causing duplicates or invalid triplets.
- error
Neglecting one of the three absolute difference conditions.
- error
Overcomplicating with unnecessary data structures when direct enumeration suffices.
进阶变体
外企场景- arrow_right_alt
Count good quadruplets with four absolute difference conditions.
- arrow_right_alt
Find maximum sum of good triplets instead of count.
- arrow_right_alt
Restrict triplets to unique values in the array.