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…

category

5

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·搜索·答案·空间

bolt

答案摘要

一个有效三角形需要满足:任意两边之和大于第三边。即: $$a + b \gt c \tag{1}$$

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个包含非负整数的数组 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 <= 1000
  • 0 <= nums[i] <= 1000
lightbulb

解题思路

方法一:排序 + 二分查找

一个有效三角形需要满足:任意两边之和大于第三边。即:

a + b \gt c \tag{1}

a + c \gt b \tag{2}

b + c \gt a \tag{3}

如果我们将边按从小到大顺序排列,即 abca \leq b \leq c,那么显然 (2)(3) 成立,我们只需要确保 (1) 也成立,就可以形成一个有效三角形。

我们在 [0,n3][0, n - 3] 范围内枚举 i,在 [i+1,n2][i + 1, n - 2] 范围内枚举 j,在 [j+1,n1][j + 1, n - 1] 范围内进行二分查找,找出第一个大于等于 nums[i]+nums[j]nums[i] + nums[j] 的下标 left,那么在 [j+1,left1][j + 1, left - 1] 范围内的 k 满足条件,将其累加到结果 ans\textit{ans}

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

1
2
3
4
5
6
7
8
9
10
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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

warning

常见陷阱

外企场景
  • 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

swap_horiz

进阶变体

外企场景
  • 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

help

常见问题

外企场景

有效三角形的个数题解:二分·搜索·答案·空间 | LeetCode #611 中等