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 pointsNum = points.size();
if (pointsNum == 0)
return 0;
int maxPointsForSlope = 1;
for (int i=0; i<pointsNum-1; i++)
{
map<double, int> curPointSlopeMap;
int samePoints = 0;
int curPointMaxSlope = 1;
for (int j=i+1; j<pointsNum; j++)
{
double slope = std::numeric_limits<double>::infinity();
if (points[i].x != points[j].x)
{
slope = 1.0*(points[i].y - points[j].y) / (points[i].x - points[j].x);
}
else if (points[i].y == points[j].y)
{
samePoints++;
continue;
}
if (curPointSlopeMap.count(slope) != 0)
{
curPointSlopeMap[slope]++;
}
else
{
curPointSlopeMap[slope] = 2;
}
if (curPointSlopeMap[slope] > curPointMaxSlope)
{
curPointMaxSlope = curPointSlopeMap[slope];
}
}
if (curPointMaxSlope + samePoints > maxPointsForSlope)
maxPointsForSlope = curPointMaxSlope + samePoints;
}
return maxPointsForSlope;
}
};