/**
* 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 globalMaxPointInLineNum = 0;
//for each point x in the set A
for(int i = 0; i < points.size(); ++i)
{
int samePtNum = 0;
int localMaxPointInLineNum = 0;
std::unordered_map<double, int> hashCntTable;
//for each point y (not equal x) in the set A
for(int j = i+1; j < points.size(); ++j)
{
double slope = std::numeric_limits<double>::infinity();//positive infinity
//judge if they are the same point
if(points[i].x == points[j].x && points[i].y == points[j].y)
{
samePtNum++;
continue;
}
//if they have the slope, recompute their slope
if(points[i].x != points[j].x)
{
slope = (double)(points[i].y-points[j].y)/(double)(points[i].x-points[j].x);
}
//save the slope in the hash count table
hashCntTable[slope]++;
//keep record of the local max
localMaxPointInLineNum = std::max(localMaxPointInLineNum, hashCntTable[slope]);
}
//keep record of the global max
globalMaxPointInLineNum = std::max(globalMaxPointInLineNum, localMaxPointInLineNum+samePtNum+1);
}
return globalMaxPointInLineNum;
}
};[LeetCode]Max Points on a Line
最新推荐文章于 2019-10-13 11:03:53 发布
本文介绍了一种高效算法,用于解决给定点集中最大共线点数的问题。通过遍历每一对点计算斜率并使用哈希表记录斜率出现频率,找出具有最多共线点的直线。
560

被折叠的 条评论
为什么被折叠?



