LeetCode 题解工作台

三角形类型

给你一个下标从 0 开始长度为 3 的整数数组 nums ,需要用它们来构造三角形。 如果一个三角形的所有边长度相等,那么这个三角形称为 equilateral 。 如果一个三角形恰好有两条边长度相等,那么这个三角形称为 isosceles 。 如果一个三角形三条边的长度互不相同,那么这个三角形称为…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

我们先对数组进行排序,然后根据三角形的定义进行分类讨论即可。 - 如果最小的两个数之和小于等于最大的数,那么无法构成三角形,返回 "none"。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始长度为 3 的整数数组 nums ,需要用它们来构造三角形。

  • 如果一个三角形的所有边长度相等,那么这个三角形称为 equilateral 。
  • 如果一个三角形恰好有两条边长度相等,那么这个三角形称为 isosceles 。
  • 如果一个三角形三条边的长度互不相同,那么这个三角形称为 scalene 。

如果这个数组无法构成一个三角形,请你返回字符串 "none" ,否则返回一个字符串表示这个三角形的类型。

 

示例 1:

输入:nums = [3,3,3]
输出:"equilateral"
解释:由于三条边长度相等,所以可以构成一个等边三角形,返回 "equilateral" 。

示例 2:

输入:nums = [3,4,5]
输出:"scalene"
解释:
nums[0] + nums[1] = 3 + 4 = 7 ,大于 nums[2] = 5 
nums[0] + nums[2] = 3 + 5 = 8 ,大于 nums[1] = 4 。
nums[1] + nums[2] = 4 + 5 = 9 ,大于 nums[0] = 3 。
由于任意两边之和都大于第三边,所以可以构成一个三角形,因为三条边的长度互不相等,所以返回 "scalene"。

提示:

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

解题思路

方法一:排序 + 分类讨论

我们先对数组进行排序,然后根据三角形的定义进行分类讨论即可。

  • 如果最小的两个数之和小于等于最大的数,那么无法构成三角形,返回 "none"。
  • 如果最小的数等于最大的数,那么是等边三角形,返回 "equilateral"。
  • 如果最小的数等于中间的数或者中间的数等于最大的数,那么是等腰三角形,返回 "isosceles"。
  • 否则,返回 "scalene"。

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def triangleType(self, nums: List[int]) -> str:
        nums.sort()
        if nums[0] + nums[1] <= nums[2]:
            return "none"
        if nums[0] == nums[2]:
            return "equilateral"
        if nums[0] == nums[1] or nums[1] == nums[2]:
            return "isosceles"
        return "scalene"
speed

复杂度分析

指标
时间complexity is O(1) since the array size is fixed at 3 and only a few comparisons are required. Space complexity is O(1) because no additional storage proportional to input is used.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Looking for immediate validation of triangle inequality.

  • question_mark

    Expect concise conditional checks rather than loops.

  • question_mark

    Interest in correctly distinguishing all triangle types without overcomplicating.

warning

常见陷阱

外企场景
  • error

    Forgetting the triangle inequality and returning a type for invalid sides.

  • error

    Confusing isosceles with equilateral when two sides are equal.

  • error

    Overcomplicating with unnecessary loops or sorting for only three elements.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Determine the type of triangle when given sides in a larger array and checking every triplet.

  • arrow_right_alt

    Return the perimeter along with the triangle type for valid triangles.

  • arrow_right_alt

    Allow floating-point side lengths and handle precision in comparisons.

help

常见问题

外企场景

三角形类型题解:数组·数学 | LeetCode #3024 简单