leetcode812

题目:

给定包含多个点的集合,从其中取三个点组成三角形,返回能组成的最大三角形的面积。

示例:
输入: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
输出: 2
解释: 
这五个点如下图所示。组成的橙色三角形是最大的,面积为2。

注意:

  • 3 <= points.length <= 50.
  • 不存在重复的点。
  •  -50 <= points[i][j] <= 50.
  • 结果误差值在 10^-6 以内都认为是正确答案。

 

解题思路:

运用三角形面积计算公式,逐个进行遍历即可

 

代码:

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(area, res);
                }
            }
        }
        return res;
    }
};

 

posted @ 2019-03-28 16:36  yxl2019  阅读(99)  评论(0编辑  收藏  举报