leetcode149. Max Points on a Line

leetcode149. Max Points on a Line

题意:

给定二维平面上的n个点,找到位于同一直线上的最大点数。

思路:

O(n^2),第一重遍历确定点,第二重遍历求确定点和剩下的点的斜率,这题对斜率的精度要求比较高。有一个特殊的办法就是用pair储存dx,dy。只要pair<dx,dy> 相等放在hash表中就是一样的,不过要对dx,dy做预处理,就是dx,dy都除以最大公约数,用一个gcd就好了。 注意一些细节部分。

  • 注意重合的点
  • 注意斜率不存在的情况

ac代码:

C++

/**
 * 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 a,int b)
    {
        return !b?a:gcd(b,a%b);
    }
    int maxPoints(vector<Point>& points) {
        int res = 0;       
        for(int i = 0; i < points.size(); i++)
        {
            map<pair<int,int>,int> hash;  
            int temp = 0;
            int countsame = 0;
            int countzero = 0; 
            for(int j = i + 1; j < points.size(); j++)
            {
                int dx = points[j].x - points[i].x;
                int dy = points[j].y - points[i].y;
                if(!dx && !dy)
                {
                    countsame ++;
                    continue;
                }
                if(!dx)
                {
                    countzero ++;
                    continue;
                }
                int d = gcd(dx, dy);
                hash[make_pair(dx/d,dy/d)] ++;
                temp = max(temp, hash[make_pair(dx/d,dy/d)]);
            }
            temp = max(temp, countzero);
            res = max(res, temp + 1 + countsame);
        }
        return res;
    }
};

python


原文地址:https://www.cnblogs.com/weedboy/p/7161365.html