[LeetCode] 3024. Type of Triangle
You are given a 0-indexed integer array nums of size 3 which can form the sides of a triangle.
A triangle is called equilateral if it has all sides of equal length.
A triangle is called isosceles if it has exactly two sides of equal length.
A triangle is called scalene if all its sides are of different lengths.
Return a string representing the type of triangle that can be formed or “none” if it cannot form a triangle.
Example 1:
Input: nums = [3,3,3]
Output: “equilateral”
Explanation: Since all the sides are of equal length, therefore, it will form an equilateral triangle.
Example 2:
Input: nums = [3,4,5]
Output: “scalene”
Explanation:
nums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5.
nums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4.
nums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3.
Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle.
As all the sides are of different lengths, it will form a scalene triangle.
Constraints:
nums.length == 3
1 <= nums[i] <= 100
三角形类型。
给你一个下标从 0 开始长度为 3 的整数数组 nums ,需要用它们来构造三角形。如果一个三角形的所有边长度相等,那么这个三角形称为 equilateral 。
如果一个三角形恰好有两条边长度相等,那么这个三角形称为 isosceles 。
如果一个三角形三条边的长度互不相同,那么这个三角形称为 scalene 。如果这个数组无法构成一个三角形,请你返回字符串 “none” ,否则返回一个字符串表示这个三角形的类型。
思路
首先做排序,对 nums 进行升序排序,保证 nums[0] ≤ nums[1] ≤ nums[2],这样只需检查一次三角不等式。
关于三角不等式:判断 nums[0] + nums[1] > nums[2]。若不满足,则无效三角,返回 “none”。
分类:
- 全等边:若 nums[0] == nums[1] && nums[1] == nums[2],返回 “equilateral”。
- 等腰三角:若 nums[0] == nums[1] || nums[1] == nums[2],返回 “isosceles”。
- 其他情况,返回 “scalene”
复杂度
时间O(1)
空间O(1)
代码
Java实现
1 |
|