[LeetCode] 149. Max Points on a Line

来源:互联网 发布:档案软件 编辑:程序博客网 时间:2024/04/26 13:55

难度等级:hard


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


题解:需要两重循环,第一重循环遍历起始点a,第二重循环遍历剩余点b。

 
    a和b如果不重合,就可以确定一条直线。
 
    对于每个点a,构建 斜率->点数 的map。
 
    (1)b与a重合,以a起始的所有直线点数+1 (用dup统一相加)
 
    (2)b与a不重合,a与b确定的直线点数+1(还需考虑a与b垂直的情况,此时斜率k是没有意义的)

代码:

/**
 * 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()==0)
            return 0;
        if(points.size()==1)
            return 1;
        int res=0;
        
        for(int i=0;i<points.size();i++){
            int curmax=1;
            map<double,int> m;
            int vcnt=0;//垂直点
            int dup=0;//重复点
            for(int j=0;j<points.size();j++){
                if(i!=j){
                    double y1=points[i].y-points[j].y;
                    double x1=points[i].x-points[j].x;
                    if(x1==0&&y1==0) //重复点
                        dup++;
                    else if(x1==0){
                        if(vcnt==0)
                            vcnt=2;
                        else
                            vcnt++;
                        curmax=max(curmax,vcnt);
                    }
                    else{
                        double k=y1/x1;
                        if(m[k]==0)
                            m[k]=2;
                        else
                            m[k]++;
                        curmax=max(curmax,m[k]);
                        
                    }
                }
                
                 
            }
            res=max(res,curmax+dup);
        }
        return res;
            
    }
};

原创粉丝点击