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.html
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:spa
3 <= points.length <= 50
.-50 <= points[i][j] <= 50
.10^-6
of the true value will be accepted as correct.
這道題給了咱們一系列的二維平面上的點,讓咱們找出任意三個點能組成的最大三角形的面積。那麼咱們只能遍歷全部的三角形面積,而後找出最大的那個。貌似這道題也沒有啥特別簡便的方法,不遍歷不行啊。遍歷任意三個點簡單,問題來了,如何經過三個頂點的座標求出三角形面積,這個可就是初中幾何題了,博主也不記得,只能上網搜一波。就是用下面這個公式便可:code
這裏面三個頂點分別是(x1, y1),(x2, y2),(x3, y3),有了公式後,本題就沒有什麼難點了,參見代碼以下:orm
解法一:htm
class Solution { public: double largestTriangleArea(vector<vector<int>>& points) { double res = 0; for (int i = 0; i < points.size(); ++i) { for (int j = i + 1; j < points.size(); ++j) { for (int k = j + 1; k < points.size(); ++k) { int x1 = points[i][0], y1 = points[i][1]; int x2 = points[j][0], y2 = points[j][1]; int x3 = points[k][0], y3 = points[k][1]; double area = abs(0.5 * (x2 * y3 + x1 * y2 + x3 * y1 - x3 * y2 - x2 * y1 - x1 * y3)); res = max(res, area); } } } return res; } };
咱們也能夠稍稍簡化一下上面的寫法,可是解題思路沒有任何區別,參見代碼以下:blog
解法二:leetcode
class Solution { public: double largestTriangleArea(vector<vector<int>>& points) { double res = 0; for (auto &i : points) { for (auto &j : points) { for (auto &k : points) { res = max(res, 0.5 * abs(i[0] * j[1] + j[0] * k[1] + k[0] * i[1]- j[0] * i[1] - k[0] * j[1] - i[0] * k[1])); } } } return res; } };
參考資料:get