149. Max Points on a Line 【LeetCode】

问题描述

在这里插入图片描述
在这里插入图片描述
题目意思是求出在同一条直线上最多的点。

入的几个坑:
1.之前定义map<Point,int>变量,Point存处理后的横纵坐标,发现map并不能对Point这个key值自动排序,然后我错误的以为只要自己写个cmp排序规则就行了,但是发现在cmp中没办法取到value值。可以用pair代替。
2.不能在双重循环之外进行比较取最大值,因为如上面的第二个例子,那四个点最后存进去的不是4而是6,因为每两个点都要比较一次。
3.注意垂直或者平行x轴这两种情况
4.注意两点重合的情况,这样每轮比较都要把他们加上。

代码如下:

/**
 * 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 gcd(int m,int n)
    {
        while(n)
        {
            int k = m%n;
            m = n;
            n = k;
        }
        return m;
    }
    int maxPoints(vector<Point>& points) {
        int res=0;
        for(int i=0;i<points.size();i++)
        {
            map<pair<int,int>,int> m;
            int chongfu = 1;
            for(int j=i+1;j<points.size();j++)
            {
                int xx = points[j].x-points[i].x;
                int yy = points[j].y-points[i].y;
                if(!xx && !yy)
                {
                    chongfu++;  //两点重合情况
                }
                else
                {
                    if(!xx && yy)
                        m[{0,points[j].x}]++;  //平行y轴,可能有多条
                    else
                    {
                        int k = gcd(xx,yy);
                        m[{xx/k,yy/k}]++;
                    }
                }
            }
            map<pair<int,int>,int>::iterator it=m.begin();
            res = max(chongfu,res);
            while(it != m.end())
            {
                res=max(it->second+chongfu,res);
                it++;
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/hhhhhh5863/article/details/89041459