[leetcode] Max Points on a Line

来源:互联网 发布:自动答题软件 编辑:程序博客网 时间:2024/06/05 17:01

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

思路:以每个点为基点,逐个遍历后续点,找出与这个点共线的点的最大个数,注意处理重复的的点,平行x轴,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) {        int len=points.size();        if(len==0) return 0;        if(len==1) return 1;        if(len==2) return 2;        map<double,int> temp;//将斜率保存在map中,以便找到相同斜率点的个数        int maxsum=0,tempsum=0;        int samepoint=0;        int tmpres=0;        int tmp=0;        int res=1;        int samex=1,samey=1;        for(int i=0;i<len;i++){                temp.clear();                for(int j=i+1;j<len;j++){                        if(points[j].x==points[i].x){                                samex++;//统计与x轴平行的点                        }                        if(points[j].y==points[i].y){                                samey++;//统计与y轴平行的点                        }                        double line;                        if(points[j].x!=points[i].x){                                line=1.0*(points[j].y-points[i].y)/(points[j].x-points[i].x);//计算斜率                                if(temp.find(line)!=temp.end()){                                        temp[line]++;                                        tmp=temp[line];                                }else{                                        temp[line]=2;                                        tmp=2;                                }                        }                        else if(points[j].y==points[i].y){                                samepoint++;//重复点的个数                                continue;                        }                           if(tmpres<tmp){                                tmpres=tmp;                        }                                     }                if(res<tmpres+samepoint){                        res=tmpres+samepoint;                }                if(res<samex){                        res=samex;                }                if(res<samey){                        res=samey;                }                samepoint=0;                samex=1;                samey=1;                tmpres=0;        }        return res;    }};


0 0
原创粉丝点击