LeetCode: Max Points on a Line [149]

【题目】

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


【题意】

    给定一堆点,要求找出一条线上的最大点数


【思路】

        没什么好的方法,从每个点P出发,遍历所有的情况
        从每个点P出发,斜率相同的点即为统一之前上的点
        注意两种特殊情况:
        1. 两个点重合(即为同一个点)
        2. 两个点的很坐标相同,即两天构成的之前垂直于X轴


【代码】

/**
 * 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) {
        int max=0;
        double INFTY = INT_MAX * 1.0;
        for(int i=0; i<points.size(); i++){
            map<double, int> pointNum;  //key是直线的斜率,value是这条直线上的点数
            int samepoints = 1;         //统计和当前点重合点的个数(包括它自己,所以初始化为1)
            int curmax=0;               //过当前这个点的所有直线的最多点数
            for(int j=0; j<points.size(); j++){
                if(i!=j){
                    //计算斜率
                    if(points[i].x==points[j].x && points[i].y==points[j].y){ 
                        samepoints++;
                        continue;
                    }
                    //x坐标相同
                    if(points[i].x==points[j].x){
                        pointNum[INFTY]++;
                        if(pointNum[INFTY]>curmax)curmax = pointNum[INFTY];
                        continue;
                    }
                    //x坐标不同
                    double slop = (points[i].y-points[j].y) * 1.0/(points[i].x-points[j].x);
                    pointNum[slop]++;
                    if(pointNum[slop] > curmax) curmax = pointNum[slop];
                }
            }
            if(curmax+samepoints > max) max = curmax+samepoints;
        }
        return max;
    }
};


猜你喜欢

转载自blog.csdn.net/HarryHuang1990/article/details/36204511