149. Max Points on a Line *HARD* 求点集中在一条直线上的最多点数

时间:2021-12-24 21:37:00

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

/**
* 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) {
int n = points.size(), i, j, ans = ;
if( == n)
return ;
for(i = ; i < n; i++)
{
map<double, int> m;
map<int, int> x, y;
int samePoint = ;
for(j = ; j < n; j++)
{
int deltaX = points[i].x - points[j].x;
int deltaY = points[i].y - points[j].y;
if( == deltaX && == deltaY)
{
samePoint++;
}
else if( == deltaX)
{
if(x.find(points[i].x) == x.end())
x[points[i].x] = ;
else
x[points[i].x]++;
}
else if( == deltaY)
{
if(y.find(points[i].y) == y.end())
y[points[i].y] = ;
else
y[points[i].y]++;
}
else
{
double t = 1.0 * deltaX / deltaY;
if(m.find(t) == m.end())
m[t] = ;
else
m[t]++;
}
}
ans = max(ans, samePoint);
for(map<double, int>::iterator it = m.begin(); it != m.end(); it++)
ans = max(ans, it->second+samePoint);
for(map<int, int>::iterator it = x.begin(); it != x.end(); it++)
ans = max(ans, it->second+samePoint);
for(map<int, int>::iterator it = y.begin(); it != y.end(); it++)
ans = max(ans, it->second+samePoint);
}
return ans;
}
};