Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
/**
* Definition for a point.
* class Point {
* int x;
* 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 || points == null) {
return 0;
}
if (points.length == 1) {
return 1;
}
int res = 1;
for (int i = 0; i < points.length; i++) {
HashMap<Float,Integer> hashMap = new HashMap<Float, Integer>();
int same = 0;
int max = 1;
for (int j = 0; j < points.length; j++) {
if (i == j) {
continue;
}
if (points[i].x == points[j].x && points[i].y == points[j].y) {
same++;
continue;
}
float tmp = (float)(points[i].y - points[j].y) / (points[i].x - points[j].x);
if (hashMap.containsKey(tmp)) {
hashMap.put(tmp, hashMap.get(tmp) + 1);
} else {
hashMap.put(tmp, 2);
}
}
for (Integer value : hashMap.values()) {
max = Math.max(max, value);
}
max += same;
res = Math.max(max, res);
}
return res;
}
}