写在前面: 三个for循环暴力求解,用到了高中学过的海伦公式,吐槽一下力扣C++测试点又bug了,本地执行代码过了测试点,然后提交平台给我报错。。。这种水题害我调试半天,还是改点代码用JS写一把过的
这是我的 力扣github仓库 ,有JavaScript和C++两个版本,每日更新。觉得有用的朋友请点点star~
C++代码
class Solution {
public:double largestTriangleArea(vector<vector<int>>& points) {int len=points.size();int m=0;for(int i=0;i<len;i++){double i_x=points[i][0],i_y=points[i][1];for(int j=i+1;j<len;j++){double j_x=points[j][0],j_y=points[j][1];for(int k=j+1;k<len;k++){double k_x=points[k][0],k_y=points[k][1];double len1 = length(i_x,i_y,j_x,j_y);double len2 = length(i_x,i_y,k_x,k_y);double len3 = length(j_x,j_y,k_x,k_y);double areas=area(len1,len2,len3);if(m<areas){ //这里力扣平台判断有问题// cout<<areas<<" ";m=areas;// cout<<m<<endl;}}}} return m;}double length(double s1_x,double s1_y,double s2_x,double s2_y){return sqrt(pow(s1_x-s2_x,2)+pow(s1_y-s2_y,2)); }double area(double a,double b,double c){double sum=(a+b+c)/2.0;return pow(sum*(sum-a)*(sum-b)*(sum-c),0.5);}
};
JS代码:
/*** @param {number[][]} points* @return {number}*/
var largestTriangleArea = function(points) {var len=points.length;var m=0;for(var i=0;i<len;i++){var i_x=points[i][0],i_y=points[i][1];for(var j=i+1;j<len;j++){var j_x=points[j][0],j_y=points[j][1];for(var k=j+1;k<len;k++){var k_x=points[k][0],k_y=points[k][1];var len1 = length(i_x,i_y,j_x,j_y);var len2 = length(i_x,i_y,k_x,k_y);var len3 = length(j_x,j_y,k_x,k_y);var areas=area(len1,len2,len3);if(m<areas){m=areas;}}}} return m;
};function length(s1_x,s1_y,s2_x,s2_y){return Math.sqrt(Math.pow(s1_x-s2_x,2)+Math.pow(s1_y-s2_y,2)); }function area(a,b,c){var sum=(a+b+c)/2.0;return Math.pow(sum*(sum-a)*(sum-b)*(sum-c),0.5);}
题目地址