您的位置:首页 > 其它

leetcode - Max Points on a Line

2014-09-13 12:34 357 查看
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) {}
* };
*/

//题目要求找到一个直线的最多点数,假设给的点的集合为points,每次从points取出一个点p1 然后,通过p1与剩下的点求出所有的斜率上的点数,
//这里用map来记录不同的点的数量,然后遍历map,找到最大的那个数量。然后重复从points取出点来计算。直到所有的点都全部遍历。
//这里注意三点,第一个是相同点处理,第二个是斜率不存在处理,第三个points的点的数量小于3,直接返回其数量的值。
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(std::vector<Point> &points) {
if(points.size() < 3) return points.size();
int PointMax = 0;
for(int i = 0; i < points.size(); i++)
{
std::map<double,int> Point_Slop;
int cnt = 0; //相同点计数
for(int j = 0; j < points.size(); j++)
{
if(i == j) continue; //同一个元素排除
if(points[i].x == points[j].x && points[i].y == points[j].y) //相同点记录
{
cnt++;
continue;
}
Point_Slop[points[i].x == points[j].x ?  INT_MAX : (double)(points[i].y - points[j].y) / (points[i].x - points[j].x)] += 1;
}
if(Point_Slop.size() == 0)
Point_Slop[INT_MAX] = 0;
//遍历map,找到最大数量的结点,copy to PointMax
for(std::map<double,int>::iterator it = Point_Slop.begin(); it != Point_Slop.end(); it++)
{
if(PointMax < it->second + cnt)
PointMax = it->second + cnt;
}
}
#if 1
std::cout << PointMax + 1 << std::endl;
#endif // 1

return PointMax + 1; //因为上面的计算没有加上本身这个点,所以,这里要PointMax + 1.
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: