Given N points on a 2D plane, find the maximum number of points that lie on the same straight line.
Take a point as the base point, get the slope of the other points and record it in map, note two points
1. The slope may be infinite
2. If the traversed point is in the same position as the base point, all slope points are added with 1
/** * Definition for a point. * Class Point {* int ×; * int y; * Point () {x = 0; y = 0;} * Point (int a, int b) {x = A; y = b;}} */public class Solution {public int maxpoints (point[] points) {if (points.length==0) return 0; if (points.length==1) return 1; map<double,integer> map = new hashmap<> (); int res = 0; for (int i=0;i<points.length;i++) {int inf = 0; int same = 0; for (int j=0;j<points.length;j++) {if (i==j) continue; if (points[j].x-points[i].x==0) {if (points[j].y-points[i].y==0) {same++; Continue } inf++; Continue } Double key = ((Double) (POINTS[J].Y-POINTS[I].Y))/(points[j].x-points[i].x); Integer value = Map.get (key); Integer newval = (value==null?1:value+1); Map.put (key, newval); } iterator<double> it = Map.keyset (). Iterator (); while (It.hasnext ()) {res = Math.maX (res, Map.get (It.next ()) +same); } res = Math.max (res, inf+same); Map.clear (); } return res+1; }}
[Leetcode] Max Points on a line