Max Points on a Line
给定二维平面上n个点,找出位于同一条直线上的最大的点的个数。
/**
* 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)
{
unsigned int size = points.size();
if(size <= 2 )
return size;
std::map<double, int> counter;
int global_max = 0;
for(int i = 0; i < size -1; ++i)
{
int k_infinity = 0;
int dup = 0;
counter.clear();
for(int j = i + 1; j < size; ++j)
{
//check same point
if(points[j].x == points[i].x && points[j].y == points[i].y)
{
dup++;
continue;
}
if(points[j].x == points[i].x)
{
k_infinity++;
continue;
}
double k = (points[j].y - points[i].y) / (points[j].x - points[i].x);
counter[k]++;
}
int local_max = 0;
for(auto it = counter.begin(); it != counter.end(); ++it)
{
if(it->second > local_max)
local_max = it->second;
}
if(k_infinity > local_max)
local_max = k_infinity;
local_max += dup +1;
if(local_max > global_max)
global_max = local_max;
}
return global_max;
}
};

浙公网安备 33010602011771号