7.6 on the two-dimensional plane, there are some points, please find the line that passes the most points.
Solution:
Similar to Leetcode:max Points on a line
We only need to "draw" an infinitely long line (not a line segment) between any two points, and use the hash list to track which line appears most often. The time complexity of this practice O (n^2), because there are altogether n^2 line segments.
By using each point with a slope other than itself (to note the absence of equality and slope), use Unorder_map to insert a K-value and accumulate the same K-value, adding one point to the line at a time. The main idea is that any point on a straight line is equal to the K value obtained from the other points, so you can calculate the number of points on the slope by calculating the slope at any point with each other.
C + + Implementation code:
#include <iostream>#include<unordered_map>#include<vector>#include<climits>using namespacestd;structpoint{intx; inty; Point (): X (0), Y (0) {} point (intAintb): X (a), Y (b) {}};intMaxpoints (Vector<point> &points) { if(Points.empty ())return 0; intn=points.size (); inti,j; intmaxnum=0; Unordered_map<Double,int>MP; for(i=0; i<n;i++) { intDuplicate=1; Mp[int_max]=0; Mp.clear (); for(j=0; j<n;j++) { if(i==j)Continue; if(points[i].x==points[j].x&&points[i].y==points[j].y) {Duplicate++; Continue; } DoubleK= (Points[i].x==points[j].x?int_max: (Double) (POINTS[I].Y-POINTS[J].Y)/(points[i].x-points[j].x)); MP[K]++; } Auto Mp_iter=Mp.begin (); while(mp_iter!=Mp.end ()) { if(mp_iter->second+duplicate>maxnum) Maxnum=mp_iter->second+Duplicate; Mp_iter++; } } returnMaxnum;}intmain () {vector<Point> Vec={point (0,0), point (1,1), point (2,2), point (388,4), point (6,3), point (0,0)}; cout<<maxpoints (VEC) <<Endl;}
careercup-Mathematics and Probability 7.6