Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
就是算在同一条直线上的点有多少个,需要注意的有几点:
1.坐标相同的点算在同一条直线上
2.斜率相同的点在同一条直线上,但特例是横坐标相同的点斜率不存在
思路是对每个点遍历剩余的点,创建一张哈希表map<double,int>,存储每个斜率对应的直线上的点数,斜率不存在时对应key值INT_MAX
AC代码:
class Solution {
public:
int maxPoints(vector<Point> &points) {
double k;
int i,j,max=0;
if(points.size()<=2)return points.size();
for(i=0;i<points.size();i++)
{
map<double,int>count;
count[INT_MIN]=0;
int samepoint=1;
for(j=0;j<points.size()&&j!=i;j++)
{
if(points[j].x==points[i].x&&points[j].y==points[i].y)
samepoint++;
else
{
double k=points[j].x==points[i].x?INT_MAX:(double)(points[j].y-points[i].y)/(double)(points[j].x-points[i].x);
count[k]++;
}
}
map<double,int>::iterator ite = count.begin();
for(ite;ite!=count.end();ite++)
{
if(ite->second+samepoint>max)
max=ite->second+samepoint;
}
}
return max;
}
};