题目地址:
https://leetcode.com/problems/largest-triangle-area/
给定平面直角坐标系中的 n n n个整数点,求三个点使得它们构成的三角形面积最大,返回面积。
对于点 A = ( x 1 , y 1 ) , B = ( x 2 , y 2 ) , C = ( x 3 , y 3 ) A=(x_1,y_1),B=(x_2,y_2),C=(x_3,y_3) A=(x1,y1),B=(x2,y2),C=(x3,y3),它们组成的三角形面积是: S = 1 2 ∣ A B ⃗ × A C ⃗ ∣ = 1 2 ∣ ( x 2 − x 1 , y 2 − y 1 ) × ( x 3 − x 1 , y 3 − y 1 ) ∣ = 1 2 [ ( x 2 − x 1 ) ( y 3 − y 1 ) − ( y 2 − y 1 ) ( x 3 − x 1 ) ] S=\frac{1}{2}|\vec{AB}\times \vec{AC}|\\=\frac{1}{2}|(x_2-x_1,y_2-y_1)\times (x_3-x_1,y_3-y_1)|\\=\frac{1}{2}[(x_2-x_1)(y_3-y_1)-(y_2-y_1)(x_3-x_1)] S=21∣AB×AC∣=21∣(x2−x1,y2−y1)×(x3−x1,y3−y1)∣=21[(x2−x1)(y3−y1)−(y2−y1)(x3−x1)]枚举所有情况即可。代码如下:
class Solution {
public:
double largestTriangleArea(vector<vector<int>>& ps) {
int n = ps.size();
auto calc = [&](vector<int>& a, vector<int>& b, vector<int>& c) {
int x1 = b[0] - a[0], y1 = b[1] - a[1];
int x2 = c[0] - a[0], y2 = c[1] - a[1];
return x1 * y2 - x2 * y1;
};
double res = 0;
for (int i = 0; i + 2 < n; i++)
for (int j = i + 1; j + 1 < n; j++)
for (int k = j + 1; k < n; k++)
res = max(res, (double)abs(calc(ps[i], ps[j], ps[k])));
return res / 2.0;
}
};
时间复杂度 O ( n 3 ) O(n^3) O(n3),空间 O ( 1 ) O(1) O(1)。