Title: Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Analysis: Fixed a point, traversing the remaining points, the period with a HashMap record two points slope and the number of slopes, the local maximum value, and then fixed another point, traversing the rest, ..., that is, two loops, the inner loop to find the local maximum value, the outer loop to update the global maximum value. Need to note: 1. The point overlap Case 2. The case of a straight line perpendicular to the X axis 3. Normal condition 4. Conditions with a slope of-0.0
Java code:
Public intmaxpoints (point[] points) {if(Points.length <= 2) { returnpoints.length; } intMax = 0; floatK =0f; for(inti = 0; i < points.length-1; i++) {//Global Maximum ValueHashmap<float, integer> HM =NewHashmap<float, integer>(); Hm.put (Float.max_value,0); intRepoint = 0; for(intj = i+1; J < Points.length; J + +) {//local maximum, fixed one point if(points[i].x = = points[j].x && points[i].y = = points[j].y) {//Dot Coincidentrepoint++; } Else if(points[i].x = = points[j].x) {//Vertical X-axisHm.put (Float.max_value, Hm.get (float.max_value) +1); } Else{k= (float) (POINTS[I].Y-POINTS[J].Y)/(points[i].x-points[j].x);//Normal situation if(k = =-0.0) {//appears -0.0K =0f; } if(!Hm.containskey (k)) {hm.put (k,1); } Else{hm.put (k, Hm.get (k)+1); } } } for(Float d:hm.keyset ()) {if(Hm.get (d) +repoint+1 >max) {Max= Hm.get (d) +repoint+1; } } } returnMax; }
Find the maximum number of points that a straight line passes through