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();
if(n<=2) return n;
map<float, int> mp;
int maxnum = 0;
for(int i = 0; i < n; i++)
{
mp.clear();
int dup = 1;
for(int j = 0; j < n; j++)
{
if(j == i)
continue;
if(points[j].x == points[i].x && points[j].y == points[i].y)
{
dup++;
continue;
}
float a = points[j].x == points[i].x ? INT_MAX : (float)(points[j].y-points[i].y)/(points[j].x-points[i].x);
mp[a]++;
}
map<float,int>::iterator it=mp.begin();
if(mp.empty())
maxnum = dup > maxnum ? dup : maxnum;
else
{
for(;it!=mp.end();++it)
{
if(it->second + dup > maxnum)
maxnum = it->second+dup;
}
}
}
return maxnum;
}
};