Given
n
points on a 2D plane, find the maximum number of points that lie on the same straight line.
public class Solution {
public int maxPoints(Point[] points) {
if(points.length <= 0) return 0;
if(points.length <= 2) return points.length;
int result = 0;
for(int i = 0; i < points.length; i++){
HashMap<String, Integer> hm = new HashMap<>();
int samex = 1;
int samep = 0;
for(int j = 0; j < points.length; j++){
if(j != i){
if((points[j].x == points[i].x) && (points[j].y == points[i].y)){
samep++;
}
if(points[j].x == points[i].x){
samex++;
continue;
}
int diffY = points[j].y - points[i].y;
int diffX = points[j].x - points[i].x;
int gcd = gcd(diffY, diffX);
String str = diffY / gcd + "-" + diffX / gcd;
if(hm.containsKey(str)){
hm.put(str,hm.get(str) + 1);
}else{
hm.put(str, 2);
}
result = Math.max(result, hm.get(str) + samep);
}
}
result = Math.max(result, samex);
}
return result;
}
private int gcd(int a, int b){
if (a == 0) return b;
return gcd(b % a, a);
}
}