Power button 812. Maximum triangle area

Title description

Given a set containing multiple points, take three points from it to form a triangle, and return the area of ​​the largest triangle that can be formed.

Example

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

note

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

Problem solving ideas

Violent problem solving: Know the coordinates of three points, find the area of ​​the triangle, and return the maximum area.
Calculation method
1: Helen's formula
2: Vector method

Code

//海伦公式
double getLength(int *point1,int *point2){
    
    
     return sqrt(      (point1[0]-point2[0])*(point1[0]-point2[0]) + 
                       (point1[1]-point2[1])*(point1[1]-point2[1])                            
                );
}
/*
向量法S = 0.5 * |A * B|= 0.5 * |X1Y2 + X2Y3 + X3Y1 -X2Y1 -X3Y2 -X1Y3|
double getArea(int *point1, int *point2, int *point3){
    return 0.5 * abs(point1[0]*ppoint2[1] + point2[0]*point3[1] + point3[0]*point1[1]
                    - point2[0]*point1[1] - point3[0]*point2[1] -point1[0]*point3[1]);
}
*/

double largestTriangleArea(int** points, int pointsSize, int* pointsColSize){
    
    
    int i,j,k;
    double a;
    double b;
    double c;
    double p;
    double s;
    double ret=0;
    for(i = 0; i < pointsSize - 2; i++) {
    
    
          for(j = i + 1; j < pointsSize - 1; j++) {
    
    
             for(k = j + 1; k < pointsSize; k++) {
    
    
                a = getLength(points[i],points[j]);
                b = getLength(points[i],points[k]);
                c = getLength(points[k],points[j]);
                p = (a+b+c)/2;
                s = sqrt(p*(p-a)*(p-b)*(p-c));
                //s=getArea(points[i], points[j], points[k]);
                ret = s > ret?  s:ret;
            }
        }
    }
    return ret;
}

link

Guess you like

Origin blog.csdn.net/qq_44722674/article/details/113097466