Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Problem Solving Ideas:
The main need to consider the case of diagonal, you can calculate the points[i] line up to a few points, and then calculate the maximum, because the calculation of the points[i], the front of the points are calculated, so do not need to take the previous points into account, so the problem can be converted to over Points[i ] The number of line maximum points, the problem-solving idea is to use a hashmap storage slope, traverse points[i] Each point behind, see and Points[i] The slope has occurred, there is a problem, how to store the slope, ideally, the slope should be expressed as a string, such as (0,0 ) and (2,4) can be stored as "1k2" such a type, which involves the problem of seeking greatest common divisor, it is cumbersome to implement, in fact, directly with a double representation can be passed, because ((double) 1/((double) integer.max_value-( Double) integer.min_value) is capable of outputting 2.3283064370807974E-10. Therefore, we can directly use double.
The Java implementation is as follows:
public int maxpoints (point[] points) {if (Points.length <= 2) return points.length;int max = 2;for (int i = 0; i < PO Ints.length; i++) {int pointmax = 1, samepointcount = 0; Hashmap<double, integer> slopecount = new hashmap<double, integer> (); Point origin = points[i];for (int j = i + 1, J < Points.length; J + +) {Point target = points[j];if (origin.x = = Target.x && ORIGIN.Y = = target.y) {samepointcount++;continue;} Double K;if (origin.x = = target.x) K = Float.positive_infinity;else if (origin.y = = target.y) K = 0;elsek = ((double) (Origi N.Y-TARGET.Y)/(double) (origin.x-target.x); if (Slopecount.containskey (k)) Slopecount.put (K, Slopecount.get (k) + 1); Elseslopecount.put (k, 2);p Ointmax = Math.max (Pointmax, Slopecount.get (k));} max = Math.max (max, Pointmax + samepointcount);} return max; }
Java for Leetcode 149 Max Points on a line