Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Straight lines that pass the same point and have equal slope must be the same line, so we just have to calculate the slope of each point and the other points, count the number of slopes, and find the maximum value. You can use double to represent the slope, use map<double, int> to count the numbers. But there are two points to note, that is:
(1) If the line is perpendicular to the x-axis, the slope is infinitely large and should be handled separately
(2) Some of the points given are the same points, at this time also to special treatment.
1 /**2 * Definition for a point.3 * struct Point {4 * int x;5 * int y;6 * Point (): X (0), y (0) {}7 * Point (int a, int b): X (a), Y (b) {}8 * };9 */Ten classSolution { One Public: A intMaxpoints (vector<point>&points) { - intres =0, same_cnt, ver_cnt, CNT; -unordered_map<Double,int>MP; the DoubleK; - for(inti =0; I < points.size (); ++i) { -same_cnt = ver_cnt = CNT =0; - mp.clear (); + for(intj =0; J < Points.size (); ++j) { - if(points[i].x = =points[j].x) { + if(Points[i].y = =points[j].y) { A++same_cnt; at Continue; -}Else { -++ver_cnt; -CNT =Max (CNT, ver_cnt); - } -}Else { inK = (Double) (POINTS[I].Y-POINTS[J].Y)/(Points[i].x-points[j].x); -++Mp[k]; toCNT =Max (CNT, mp[k]); + } - } theres = max (res, CNT +same_cnt); * } $ returnRes;Panax Notoginseng } -};
[Leetcode] Max Points on a line