很简单,看线段的斜率就可以了。
/**
* Definition for a point.
* struct Point {
* int x;
* int y;
* Point() : x(0), y(0) {}
* Point(int a, int b) : x(a), y(b) {}
* };
*/
class Solution {
public:
int maxPoints(vector<Point>& points) {
if(points.empty())return 0;
else if(points.size()==1)return 1;
int res = 0;
for(int i=0;i<points.size();i++){
int curmax = 1;
unordered_map<double,int>kcnt;
int vcnt = 0;
int dup = 0;
for(int j=0;j<points.size();j++){
if(j!=i){
double deltax = points[i].x-points[j].x;
double deltay = points[i].y-points[j].y;
if(deltax==0&&deltay==0)dup++;
else if(deltax==0){
if(vcnt==0)
vcnt+=2;
else
vcnt++;
curmax =max(curmax,vcnt);
}
else {
double k = deltay/deltax;
if(kcnt[k]==0)
kcnt[k]=2;
else
kcnt[k]++;
curmax = max(curmax,kcnt[k]);
}
}
}
res = max(res,dup+curmax);
}
return res;
}
};

本文介绍了一种算法,用于找出平面上共线点的最大数量。通过计算各点之间的斜率并利用哈希表统计斜率出现的次数来实现。适用于解决几何问题中关于点共线的判断。

被折叠的 条评论
为什么被折叠?



