3899. Angles of a Triangle
Description
You are given a positive integer array sides of length 3.
Determine if there exists a triangle with positive area whose three side lengths are given by the elements of sides.
If such a triangle exists, return an array of three floating-point numbers representing its internal angles (in degrees), sorted in non-decreasing order. Otherwise, return an empty array.
Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: sides = [3,4,5]
Output: [36.86990,53.13010,90.00000]
Explanation:
You can form a right-angled triangle with side lengths 3, 4, and 5. The internal angles of this triangle are approximately 36.869897646, 53.130102354, and 90 degrees respectively.
Example 2:
Input: sides = [2,4,2]
Output: []
Explanation:
You cannot form a triangle with positive area using side lengths 2, 4, and 2.
Constraints:
sides.length == 31 <= sides[i] <= 1000
Solutions
Solution 1: Sorting + Math
Thinking
Decide whether three sides form a positive-area triangle; if so, return the interior angles in degrees, nondecreasing.
After sorting, \(a+b \le c\) fails. Otherwise the law of cosines gives two angles and the third is \(180^\circ\) minus those.
Sorting the sides also orders the opposite angles, so the triple is already nondecreasing.
Inverse cosine converted to degrees stays within the allowed error.
We first sort the array \(\textit{sides}\) in non-decreasing order, and denote the three side lengths as \(a\), \(b\), and \(c\), where \(a \le b \le c\).
According to the triangle inequality, if \(a + b \le c\), then these three sides cannot form a triangle with positive area, so we return an empty array directly.
Otherwise, the three sides can form a valid triangle. By the law of cosines, we have:
Therefore, we can compute angles \(A\) and \(B\) separately. Finally, using the fact that the sum of the internal angles of a triangle is \(180^\circ\), we get:
Finally, we return the three internal angles.
The time complexity is \(O(1)\), and the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 | |