您的位置:首页 > 其它

Max Points on a Line

2015-08-28 20:44 281 查看
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

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) {}
* };
*/
#define INF_MAX 0x3fffffff

class Solution {
public:
int maxPoints(vector<Point>& points) {
int len = points.size();
if(len <= 2) return len;
unordered_map<double, int> um;
int maxNum = 0;
for(int i = 0; i < len; ++i)
{
um.clear();
int num = 0;
for(int j = i + 1; j < len; ++j)
{
if(points[i].x == points[j].x && points[i].y == points[j].y)
{
num++;
continue;
}
double slope = points[i].x == points[j].x ? INF_MAX :
(points[j].y - points[i].y) * 1.0 / (points[j].x - points[i].x);
if(!um.count(slope)) um[slope] = 2;
else um[slope]++;
}
maxNum = max(maxNum, num + 1);
for(auto iter = um.begin(); iter != um.end(); ++iter)
if(maxNum  < iter->second + num) maxNum = iter->second + num;
}

return maxNum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: