Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
思路:
这是一道数学题,我的思路就是枚举,首先选两个不同的点确定一条直线,然后遍历所有的点,判断每个点是否在该直线上,若是,计数器就加一。本题目思路很简单,但是陷阱比较多。比如,如果所有的点都相同,这种情况能确定无数条直线,但是所有点仍然是共线的,所以需要单独考虑。还有一个亮点就是判断3点共线的方法,是用的乘法,而不是除法,这样防止了判断除数为0的情况。
Solution:
/**
* 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)
{
if(points.size()==0)return 0;
if(points.size()==1)return 1;
int i,cnt,tmax=1;
for(i=1;i<points.size() && (points[i].x==points[0].x && points[i].y==points[0].y);i++);
if(i == points.size())return i;
for(i=0;i<points.size();i++)
{
for(int j=i+1;j<points.size();j++)
{
if(points[i].x==points[j].x && points[i].y==points[j].y)
continue;
cnt=0;
for(int k=0;k<points.size();k++)
{
if(((points[i].x-points[j].x)*(points[i].y-points[k].y)) == ((points[i].x-points[k].x)*(points[i].y-points[j].y)))
cnt++;
}
if(cnt>tmax)tmax=cnt;
}
}
return tmax;
}
};