Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
/** * 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; } };
LeetCode: Max Points on a Line [149],布布扣,bubuko.com
LeetCode: Max Points on a Line [149]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/36204511