Given n points on a 2D plane, find the maximum number of points that lie on the
same straight line.
判断二维点共线的最大数目。
两个点共线就是斜率相等,当垂直和重合的点是不能计算斜率的,需要另判断。
public int maxPoints(Point[] points) {
if(points==null||points.length<=0)
return 0;
int max=0;
HashMap<Double,Integer> result=new HashMap<Double, Integer>();
for(int i=0;i<points.length;i++){
int duplicate=1,vertical=0;
for(int j=i+1;j<points.length;j++){
if(points[i].x==points[j].x){
if(points[i].y==points[j].y)
duplicate++;
else
vertical++;
}else{
double slope=points[i].y==points[j].y?0.0:
1.0*(points[i].y-points[j].y)/(points[i].x-points[j].x);
if(result.containsKey(slope))
result.put(slope, result.get(slope)+1);
else
result.put(slope, 1);
}
}
for(Integer in:result.values())
max=Math.max(max, duplicate+in);
max=Math.max(max, vertical+duplicate);
result.clear();
}
return max;
}