Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Solution
/** * Definition for a point. * class Point { * int x; * int y; * Point() { x = 0; y = 0; } * Point(int a, int b) { x = a; y = b; } * } */publicclassSolution {publicintmaxPoints(Point[] points) {if (points ==null||points.length==0) return0;int max =0;for (int j =0; j <points.length; j++) {Map<Double,Integer> map =newHashMap<>();Point pivot = points[j];int special=0;int same =0;for (int i =0; i <points.length; i++) {if (pivot.x== points[i].x&&pivot.y== points[i].y) { same++; } elseif (pivot.x== points[i].x) { special++; } else {double slope =slope(pivot, points[i]);map.merge(slope,1, (a, b) -> a + b); } }for (Integer in :map.values()) {if (special < in) { special = in; } } max = special + same > max ? special + same : max; }return max; }publicdoubleslope(Point point1,Point point2) {return (point1.y-point2.y) / (float) (point1.x-point2.x); }}