leetcode 149 Max Points on a Line
参考: https://www.cnblogs.com/grandyang/p/4579693.html
https://www.iteye.com/blog/yiminghe-568666 三点共线问题判断
解法一:从第一个节点开始,找与它在同一条线上的;如果三点共线,则x2-x0/y2-y0=x1-x0/y1-y0;每一轮循环,能找到大于i的点中,与points[i]共线的所有点。
class Solution { public: int maxPoints(vector<vector<int>>& points) { int re=0; for(int i=0;i<points.size();++i) { map<pair<int,int>,int> m; int dup=1;//至少有points[i]这个节点 for(int j=i+1;j<points.size();++j) { if(points[j][0]==points[i][0]&&points[j][1]==points[i][1]) { ++dup;continue; } int dx=points[j][0]-points[i][0]; int dy=points[j][1]-points[i][1]; int d=gcd(dx,dy); ++m[{dx/d,dy/d}]; } re=max(re,dup); for(auto& t:m) { re=max(re,t.second+dup); } } return re; } int gcd(int a,int b) { return b==0?a:gcd(b,a%b); } };
解法二:如果三点共线,则三点形成的图形的面积为0.
class Solution { public: int maxPoints(vector<vector<int>>& points) { int re=0; for(int i=0;i<points.size();++i) { int dup=1; for(int j=i+1;j<points.size();++j) { int cnt=0; long long x1=points[i][0],x2=points[j][0],y1=points[i][1],y2=points[j][1]; if(x1==x2&&y1==y2) {++dup;continue;} for(int k=0;k<points.size();++k) { int x3=points[k][0],y3=points[k][1]; if(x1*y2+x2*y3+x3*y1-x1*y3-x2*y1-x3*y2==0) ++cnt; } re=max(re,cnt); } re=max(re,dup); } return re; } };