三角形类型
难度:
标签:
题目描述
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
代码结果
运行时间: 20 ms, 内存: 15.9 MB
/*
* Using Java Streams to determine the type of triangle.
* - If all sides are equal, it's an equilateral triangle.
* - If exactly two sides are equal, it's an isosceles triangle.
* - If all sides are different, it's a scalene triangle.
* - If it can't form a triangle, return "none".
*/
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class TriangleTypeStream {
public static String triangleType(int[] nums) {
// Check if the given sides can form a triangle
if (nums[0] + nums[1] <= nums[2] || nums[0] + nums[2] <= nums[1] || nums[1] + nums[2] <= nums[0]) {
return "none";
}
// Count occurrences of each side length
Map<Integer, Long> sideCount = Arrays.stream(nums).boxed()
.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
// Determine triangle type based on side counts
if (sideCount.size() == 1) {
return "equilateral";
} else if (sideCount.size() == 2) {
return "isosceles";
} else {
return "scalene";
}
}
public static void main(String[] args) {
int[] nums1 = {3, 3, 3};
int[] nums2 = {3, 4, 5};
System.out.println(triangleType(nums1)); // Output: equilateral
System.out.println(triangleType(nums2)); // Output: scalene
}
}
解释
方法:
首先,这个代码通过排序数组a来简化三角形形状的判断。数组排序后,只需要检查最小的两个数之和是否大于第三个数(最大的数)来判断是否能构成三角形。如果不能构成三角形,返回'none'。如果可以构成三角形,接着检查三条边的关系:如果三条边相等,返回'equilateral';如果有两条边相等,返回'isosceles';如果三条边都不相等,返回'scalene'。代码中,判断等边三角形的条件存在错误,因为它比较了最大边和最小边是否相等,这总是错误的,正确应该是检查三边是否相等。
时间复杂度:
O(1)
空间复杂度:
O(1)
代码细节讲解
🦆
在判断是否能构成三角形时,为什么是比较最小的两个数之和与第三个数?是否有特定的数学定理支持这种判断方法?
▷🦆
代码中提到的错误是关于等边三角形的判断,请问如何正确判断一个三角形是否为等边三角形?
▷🦆
如果数组中的数字有重复,这会影响三角形类型的判断吗?例如,如果数组是 [2, 2, 4],输出应该是什么?
▷