[Leetcode] 812. Largest Triangle Area 解題報告
阿新 • • 發佈:2019-02-11
題目:
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; } };