Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
For each point, examine the slope of the line from other points to it, using HashMap to correspond the slope to the number of points.
One thing to note is the special slope, such as two-point repetition and two-point horizontal axis. So it's better to use string to indicate the slope
Get the slope function:
1 PublicString Getslope (Point p1, point p2)2 {3 if(p1.x==p2.x && p1.y==p2.y)4 return"Any";5 Else if(p1.x==p2.x)6 return"INF";7 Else if(p1.y==p2.y)8 return"0";9 ElseTen { One Doubletemp = p2.y-p1.y; Atemp = temp/(p2.x-p1.x); - returnTemp+ ""; - } the}
(because 0 of the double type may be represented as "0.0", it is necessary to list the ordinate as 0 separately)
Every two points slope, there are three cases: 1: Two points repeat, increase overlap value, a heavy loop to find the number of temporary maximum tempmax after adding. 2: The new effective slope: directly into the HashMap and its corresponding point value of 2, and refresh the maximum number of points tempmax. 3: There is a slope: Update the point value (+1) corresponding to the slope, and refresh the Tempmax.
Tempmax the number of base points is 1, the end of a cycle plus the number of repeating points overlap, compared to the total max value.
Here is the code:
1 Public intmaxpoints (point[] points) {2 if(points.length==0)3 return0;4 if(points.length==1)5 return1;6 if(points.length==2)7 return2;8 9 intmax = 2;Ten for(inti=0;i<points.length;i++) One { Ahashmap<string, integer> hs =NewHashmap<string, integer>(); - intOverlap = 0; - intTempmax = 1; the for(intj=i+1;j<points.length;j++) - { -String SLP =Getslope (Points[i],points[j]); - if(Slp.equals ("any")) +overlap++; - Else if(!Hs.containskey (SLP)) + { AHs.put (SLP, 2); atTempmax = Math.max (tempmax,2); - } - Else - { - intNumber = Hs.get (SLP) + 1; - Hs.put (SLP, number); inTempmax =Math.max (Tempmax, number); - } to } +max = Math.max (max, tempmax+overlap); - } the returnMax; *}
TWAIN: Double saving slope is not accurate, the most accurate or should use the quotient and the remainder of a pair of numbers to save.
[Leetcode] [JAVA] Max Points on a line