Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
分析:给定一个点,穷举剩余点,计算每一对点的斜率。由于有一个定点,所以如果计算出的斜率相同,则两点与给定点在同一直线上。
map <float,int> number;
int max = 0;
if(points.size() <= 2)
return points.size();
for(int i = 0; i < points.size() ; i++)
{
number.clear();
int samePoints = 0;
for(int j = 0; j < points.size() ; j++)
{
if(points[i].x == points[j].x && points[i].y == points[j].y)
{
samePoints ++;
continue;
}
float k = points[i].x == points[j].x ? INT_MAX :(float) ( points[j].y - points[i].y ) / (points[j].x - points[i].x);
number[k] ++;
}
if(number.size() == 0 && max < samePoints)
max = samePoints;
for(map<float,int>::iterator it = number.begin(); it != number.end() ; it++)
{
if(max < it->second + samePoints )
max = (it->second + samePoints);
}
}
return max;
注意几点特殊情况:
1、两点重复
2、斜率不存在的点(与y轴平行)
已AC
120ms