Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.\
分析:从每一个点(startPoint)出发,统计到其他点的斜率。在map中存储key=斜率,value=点数量。遇到与startPoint点重合的点,在计算所有点数量时需要加上重合点的总数。另外需要注意int除法转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; }
* }
*/
public class Solution {
/**
* @param points an array of point
* @return an integer
*/
public int maxPoints(Point[] points) {
if(points == null) return 0;
if(points.length < 3) return points.length;
HashMap<Double, Integer> res = new HashMap<Double, Integer>();
int max = 0;
for(int i = 0; i < points.length; i++) {
res.clear();//important
int startPoint = 1;//a
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) {
startPoint++;
continue;
}
int y = points[i].y - points[j].y;
int x = points[i].x - points[j].x;
double slope = 0.0;
if(x == 0) {
slope = Integer.MAX_VALUE;
} else {
slope = 1.0 * y / x;
}
res.put(slope, res.containsKey(slope) ? res.get(slope) + 1 : 1);
}
if (res.keySet().size() == 0) {
max = startPoint > max ? startPoint : max;
} else {
for (double key : res.keySet()) {
max = Math.max((startPoint + res.get(key)), max);
}
}
}
return max;
}
}