Problem description
Title means to find the most points on the same line.
Several pits entered:
1. Before defining the map < Point, int > variable, and the horizontal and vertical coordinates after Point storage, I found that map could not automatically sort the key value of Point. Then I mistakenly thought that as long as I wrote a cmp sorting rule, I found that I could not get the value value in cmp. It can be replaced by pair.
2. It is not allowed to take the maximum value for comparison outside the double cycle, because as the second example above, the last four points are not 4 but 6, because every two points should be compared.
3. Pay attention to vertical or parallel x-axis
4. Pay attention to the coincidence of two points, so that they should be added to each round of comparison.
The code is as follows:
/** * 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 gcd(int m,int n) { while(n) { int k = m%n; m = n; n = k; } return m; } int maxPoints(vector<Point>& points) { int res=0; for(int i=0;i<points.size();i++) { map<pair<int,int>,int> m; int chongfu = 1; for(int j=i+1;j<points.size();j++) { int xx = points[j].x-points[i].x; int yy = points[j].y-points[i].y; if(!xx && !yy) { chongfu++; //Coincidence of two points } else { if(!xx && yy) m[{0,points[j].x}]++; //Parallel y-axis, possibly multiple else { int k = gcd(xx,yy); m[{xx/k,yy/k}]++; } } } map<pair<int,int>,int>::iterator it=m.begin(); res = max(chongfu,res); while(it != m.end()) { res=max(it->second+chongfu,res); it++; } } return res; } };