问题描述:已知二维平面上n个点,寻找在同一直线上的点数最大值。双层for循环,有注释.
/**
* 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) {
int len = points.size();
if(len == 0)
return 0;
if(len == 1)
return 1;
int res = 0;
for(int i = 0; i < len; ++i) //每个点与其余所有点之间,在同一直线上的点数.
{
map<double, int> mp;//<斜率, 点数>
int curmax = 1;
int vcnt = 0;//垂直的点的数目
int dup = 0;//重复的点的数目
for(int j = i + 1; j < len; ++j) //最大点数为重叠点数+max(垂直点数,斜率上的点数),垂直无斜率,平行斜率为0.
{
double x = points[i].x - points[j].x;
double y = points[i].y - points[j].y;
if(x == 0.000 && y == 0.000)
++dup;
else if(x == 0.000)
{
if(vcnt == 0)
vcnt = 2;
else
++vcnt;
curmax = curmax > vcnt ? curmax : vcnt;
}
else
{
double k = y/x;
if(mp[k] == 0)
mp[k] = 2;
else
++mp[k];
curmax = curmax > mp[k] ? curmax : mp[k];
}
}
res = res > curmax ? res : curmax + dup; //外层循环更新
}
return res;
}
};