首页 > 代码库 > LeetCode:Max Points on a Line

LeetCode:Max Points on a Line

题目描写叙述:

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.


解题思路:暴力求解。以每一个点为中心,然后遍历剩余的点。对每一个点。初始化一个map,以pair<dx,dy>为key(dx,dy为两点之间x坐标与y坐标的差除以他们的最大公约数之后得到的结果),value为直线上点的个数。

一遍遍历结束后得到与当前i点共线的点的个数的最大值。将该得到的最大值与当前的最大值比較,假设比它大。则更新当前最大值。当每一点都遍历结束后,就能得到共线最多点的数目。


代码:

int Solution::maxPoints(vector<Point> &points)
{
    int size = points.size();
    int result = 0;
    if(size <= 2)
        return size;
    for(int i = 0;i < size;i++)
    {
        int vertical = 0;
        int samePoint = 0;
        int max_temp = 0;
        map<pair<int,int>,int> k;

        for(int j = 0;j < size;j++)
        {
            if(points[j].x == points[i].x && points[j].y == points[i].y)
                samePoint++;
            else if(points[j].x - points[i].x == 0)
                vertical++;
            else
            {
                int dx = points[i].x - points[j].x;
                int dy = points[i].y - points[j].y;
                int gcd = GCD(dx,dy);
                dx = dx/gcd;
                dy = dy/gcd;
                k[make_pair(dx,dy)]++;
                if(max_temp < k[make_pair(dx,dy)])
                    max_temp = k[make_pair(dx,dy)];
            }
            if(vertical > max_temp)
                max_temp = vertical;
        }
        if((max_temp+samePoint+1)> result)
            result = max_temp;
    }
    return result;
}

int Solution::GCD(int a,int b)
{
    if(b == 0)
        return a;
    else
        return GCD(b,a%b);
}


LeetCode:Max Points on a Line