
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) {} * }; */ int maxPoints(vector<Point> &points) { unordered_map<double,int>mp; int res = 0; for(int i=0; i<points.size(); i++){ mp.clear(); int theSame = 0, vertical = 0, maxSlope = 0; for(int j=0; j<points.size(); j++){ if(points[i].x == points[j].x){ if(points[i].y == points[j].y){ theSame++;//同一个点,没有这个会差1 } else{//垂直 vertical++; } } else{ double slope = (points[j].y-points[i].y)*1.0/(points[j].x-points[i].x); mp[slope]++;//计数 maxSlope = max(maxSlope,mp[slope]); } } int maxSingle = max(maxSlope,vertical) + theSame;//单点为基点,最多的点在直线上 res = max(maxSingle,res); } return res;}




近期评论