美文网首页
149. Max Points on a Line

149. Max Points on a Line

作者: 想学会飞行的阿番 | 来源:发表于2018-10-13 00:58 被阅读6次

    思路:这题的思路很简单,就是统计由每个函数上的点的数量,问题在于:
    1.有重复点
    2.对于垂直于x轴的线怎么处理
    3.如果用double,那么对于斜率非常接近怎么处理
    特殊用例:[0,MAX_INT-1,MAX_INT-2]
    discussion里看到的大牛思路:
    y0/x0 = (y2-y1)/(x2-x1) = (y3-y2)/(x3-x2) = a
    b = y1-a*x1
    利用辗转相除法,找到a,b

    class Solution {
    public:
        int getGCD(int a,int b){
            if(b == 0)return a;
            return getGCD(b,a%b);
        }
        int maxPoints(vector<Point>& points) {
            int n = points.size();
            if(n<2) return n;
            int result = 0;
            for(int i=0;i<n;i++)
            {
                map<pair<int,int>,int> lines;
                int v = 0;//垂直
                int over = 0;//重合
                int tempmax = 0;//最大
                for(int j =i+1;j<n;j++)
                {
                    if(points[j].x == points[i].x && points[j].y == points[i].y){
                        over++;
                        continue;
                    }
                    if(points[j].x == points[i].x)
                    {
                        v++;
                        tempmax = max(tempmax,v);
                        continue;
                    }
                    int a = points[j].x - points[i].x;
                    int b = points[j].y - points[i].y;
                    int gcd = getGCD(a,b);
                    a /=gcd;
                    b /=gcd;
                    lines[make_pair(a,b)]++;
                    tempmax = max(tempmax,lines[make_pair(a,b)]);
                    }
                 result = max(result,over+tempmax+1);
                }
            return result;
            }
    };
    

    相关文章

      网友评论

          本文标题:149. Max Points on a Line

          本文链接:https://www.haomeiwen.com/subject/vivnaftx.html