Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
算斜率的时候一定注意要格式转换,integer-〉double
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
import java.util.Hashtable;
public class Solution {
public int maxPoints(Point[] points) {
if(points.length < 1)
return 0;
int res = 0;
Hashtable<Double, Integer> table = new Hashtable<Double, Integer>();
for(int i = 0; i < points.length; i++){
table.clear();
int max = 0;
int duplicate = 1;
int vertical = 0;
for(int j = 0; j < points.length; j++){
if(j == i)
continue;
if(points[j].x == points[i].x && points[j].y == points[i].y){
duplicate++;
continue;
}
if(points[j].x == points[i].x){
vertical++;
continue;
}
double k = (double)(points[j].y - points[i].y) / (points[j].x - points[i].x);
if(!table.containsKey(k))
table.put(k, 1);
else
table.put(k, table.get(k) + 1);
}
for(Iterator<Double> it = table.keySet().iterator(); it.hasNext();){
int cur = table.get(it.next());
max = max > cur ? max : cur;
}
max = max > vertical ? max : vertical;
max += duplicate;
res = res > max ? res : max;
}
return res;
}
}