Description
You have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points.
imageExample:
Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2
Explanation:
The five points are show in the figure below. The red triangle is the largest.
Notes:
-
3 <= points.length <= 50
. - No points will be duplicated.
-
-50 <= points[i][j] <= 50
. - Answers within
10^-6
of the true value will be accepted as correct.
Solution
Iteration + Math, O(n ^ 3), S(1)
计算三角形面积是有公式的!(感觉是小学生数学题...惭愧啊)
image.png image.png
class Solution {
public double largestTriangleArea(int[][] points) {
double maxArea = 0;
if (points == null || points.length < 3 || points[0].length < 2) {
return maxArea;
}
int n = points.length;
for (int i = 0; i < n - 2; ++i) {
for (int j = i + 1; j < n - 1; ++j) {
for (int k = j + 1; k < n; ++k) {
double area = area(points[i], points[j], points[k]);
maxArea = Math.max(area, maxArea);
}
}
}
return maxArea;
}
public double area(int[] P, int[] Q, int[] R) {
return 0.5 * Math.abs(P[0]*Q[1] + Q[0]*R[1] + R[0]*P[1]
-P[1]*Q[0] - Q[1]*R[0] - R[1]*P[0]);
}
}
网友评论