[leetcode] Max Points on a Line

来源:互联网 发布:mac 下载不在dock 编辑:程序博客网 时间:2024/06/05 15:19

Max Points on a Line

以点为中心暴力枚举。斜率相同点共线。

注意:重合点,与y轴平行。


/** * 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;        unordered_map<double,int> slope_cnt;//斜率计数        for(int i=0;i<points.size()-1;i++){            slope_cnt.clear();            int samePointNum=0;//与i重合的点            int point_max=1;//与i共线的最大点数                        for(int j=i+1;j<points.size();j++){                double slope;//斜率                if(points[i].x==points[j].x){                    if(points[i].y==points[j].y){//点重合                        ++samePointNum;                        continue;                    }else{                        slope=std::numeric_limits<double>::infinity();//平行Y轴,斜率无穷大                    }                }else{                    slope=1.0*(points[i].y-points[j].y)/(points[i].x-points[j].x);                }                int cnt=0;                if(slope_cnt.find(slope)!=slope_cnt.end()){//已有记录                    cnt=++slope_cnt[slope];                }else{                    cnt=2;                    slope_cnt[slope]=cnt;                }                if(point_max<cnt){//更新point_max                    point_max=cnt;                }            }            res=max(res,point_max+samePointNum);//        }        return res;    }};


0 0
原创粉丝点击