题目:
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.
Example: 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.
思路:
我刚刚开始的时候觉得可能有比暴力法更好的算法,后来还是没发现,就只好用暴力法了。算法的时间复杂度是O(n^3),其中n是points中顶点的个数。
还有一种方法,就是我们知道面积最大的三角形的三个顶点一定是位于points的凸包上的。所以可以首先用O(nlogn)的时间复杂度求出points的凸包,然后再对凸包上的顶点采用暴力搜索,这样时间复杂度就降为O(m^3),其中m是points的凸包上的顶点的个数。然而在最坏情况下O(m) == O(n),所以算法的时间复杂度并没有实质的改进。
代码:
class Solution { public: double largestTriangleArea(vector<vector<int>>& points) { double max_area = 0.0, area = 0.0; for (auto &p1 : points) { for (auto &p2 : points) { for (auto &p3 : points) { area = abs(p1[0] * p2[1] + p2[0] * p3[1] + p3[0] * p1[1] - p2[0] * p1[1] - p3[0] * p2[1] - p1[0] * p3[1]) / 2.0; max_area = max(max_area, area); } } } return max_area; } };