leetcode[149]Max Points on a Line
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) { if(points.size()<3)return points.size(); int sizeMax=0; for(int i=0;i<points.size();i++) { int repeat=1; map<double,int> smap; smap.clear(); for(int j=0;j<points.size();j++) { if(i==j)continue; if(points[i].x==points[j].x&&points[i].y==points[j].y) { repeat++; continue; } double k=points[i].x==points[j].x?INT_MAX:double(points[j].y-points[i].y)/(points[j].x-points[i].x); smap[k]++; } if(smap.size()==0) { sizeMax=sizeMax>repeat?sizeMax:repeat; continue; } for(map<double,int>::iterator iter=smap.begin();iter!=smap.end();iter++) { sizeMax=sizeMax>(iter->second+repeat)?sizeMax:(iter->second+repeat); } } return sizeMax; } };