[leecode]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.

解法

  • 使用两层循环,对于每一个点,遍历其它点,计算当前点其它点斜率,斜率相同即说明共线
  • 需要注意的是垂直共线重合的点不能计算斜率,因此我们把其它点分为三类
    • 垂直共线的(不包含重合点)
    • 非垂直共线的(不包含重合点)
    • 重合的
  • 则与当前点共线的最大点数量是
    curPointMax = max(A, B) + C
    
    • A:垂直共线点的最大数量
    • B:非垂直共线点的最大数量
    • C:重合点数量
  • 对于每个点都计算curPointMax,最大的curPointMax即为所要的结果
  • 代码实现
    	/**
     * 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 maxPoints(vector<Point> &points) {
            if(points.size() < 3)
                return points.size();
            
            int res = 0;
            for(int i = 0; i < points.size(); ++i) {
                unordered_map<double, int> ratio2count; // 哈希表<斜率,点数量>
                int vCnt = 0; // 垂直共线
                int dupCnt = 0; // 重合点
                int curMax = 1;
                for(int j = i + 1; j < points.size(); ++j) {
                    if(points[i].x == points[j].x && points[i].y == points[j].y) // 重合点
                        ++dupCnt;
                    else if(points[i].x == points[j].x) { // 垂直共线
                        vCnt = vCnt == 0 ? 2 : vCnt + 1;
                        curMax = max(curMax, vCnt);
                    }
                    else { // 非垂直共线
                        double ratio = (double)(points[i].y - points[j].y) / (points[i].x - points[j].x);
                        if(ratio2count.find(ratio) == ratio2count.end())
                            ratio2count[ratio] = 2;
                        else
                            ++ratio2count[ratio];
                        curMax = max(curMax, ratio2count[ratio]);
                    }
                }
                res = max(res, curMax + dupCnt);
            }
            
            return res;
        }
    };
    

猜你喜欢

转载自blog.csdn.net/zhwenx3/article/details/86698171