Problem 2:
Sides of a triangle
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 == 3
• 1 <= sides[i] <= 1000
class Solution {
public double[] internalAngles(int[] sides) {
Arrays.sort(sides);
if (sides[0] + sides[1] > sides[2] &&
sides[1] + sides[2] > sides[0] &&
sides[0] + sides[2] > sides[1]) {
double A = angleFromSides(sides[1], sides[2], sides[0]);
double B = angleFromSides(sides[0], sides[2], sides[1]);
double C = angleFromSides(sides[0], sides[1], sides[2]);
double[] angles = {A, B, C};
Arrays.sort(angles); // non-decreasing order
return angles;
} else {
return new double[0];
}
}
private static double angleFromSides(int side1, int side2, int opposite) {
double numerator = (side1 * side1) + (side2 * side2) - (opposite * opposite);
double denominator = 2.0 * side1 * side2;
double cosValue = numerator / denominator;
// Numerical safety: clamp to [-1, 1]
cosValue = Math.max(-1.0, Math.min(1.0, cosValue));
return Math.toDegrees(Math.acos(cosValue));
}
}
Test cases:
Case 0:
Input
sides =
[3,4,5]
Output
[36.86990,53.13010,90.00000]
Expected
[36.86990,53.13010,90.00000]
Case 1:
Input
sides =
[2,4,2]
Output
[]
Expected
[]
No comments:
Post a Comment