LeetCode 题解工作台
有效三角形的个数
给定一个包含非负整数的数组 nums ,返回其中可以组成三角形三条边的三元组个数。 示例 1: 输入: nums = [2,2,3,4] 输出: 3 解释: 有效的组合是: 2,3,4 (使用第一个 2) 2,3,4 (使用第二个 2) 2,2,3 示例 2: 输入: nums = [4,2,3,4…
5
题型
6
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
一个有效三角形需要满足:任意两边之和大于第三边。即: $$a + b \gt c \tag{1}$$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给定一个包含非负整数的数组 nums ,返回其中可以组成三角形三条边的三元组个数。
示例 1:
输入: nums = [2,2,3,4] 输出: 3 解释:有效的组合是: 2,3,4 (使用第一个 2) 2,3,4 (使用第二个 2) 2,2,3
示例 2:
输入: nums = [4,2,3,4] 输出: 4
提示:
1 <= nums.length <= 10000 <= nums[i] <= 1000
解题思路
方法一:排序 + 二分查找
一个有效三角形需要满足:任意两边之和大于第三边。即:
a + b \gt c \tag{1}
a + c \gt b \tag{2}
b + c \gt a \tag{3}
如果我们将边按从小到大顺序排列,即 ,那么显然 (2)(3) 成立,我们只需要确保 (1) 也成立,就可以形成一个有效三角形。
我们在 范围内枚举 i,在 范围内枚举 j,在 范围内进行二分查找,找出第一个大于等于 的下标 left,那么在 范围内的 k 满足条件,将其累加到结果 。
时间复杂度 ,空间复杂度 。其中 是数组的长度。
class Solution:
def triangleNumber(self, nums: List[int]) -> int:
nums.sort()
ans, n = 0, len(nums)
for i in range(n - 2):
for j in range(i + 1, n - 1):
k = bisect_left(nums, nums[i] + nums[j], lo=j + 1) - 1
ans += k - j
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Sorting the array before counting triplets
- question_mark
Using two pointers or binary search for the third side
- question_mark
Avoiding O(n^3) brute-force enumeration
常见陷阱
外企场景- error
Not sorting the array first, causing incorrect triangle checks
- error
Ignoring duplicate numbers leading to miscounted triplets
- error
Miscalculating the range of the third side or using incorrect indices
进阶变体
外企场景- arrow_right_alt
Count triangles with perimeter below a given threshold
- arrow_right_alt
Find all unique triplets instead of counting them
- arrow_right_alt
Allow negative numbers and determine valid triangle counts accordingly