Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
遍历所有点,计算每两个点的斜率k,并用map存放当前固定点此斜率的点的个数;
注意可能存在重复点,用dup记录,当前点为1,所以dup初始化为1;
注意double类型0.0的表示;
与y轴平行时,斜率表示为Double.MAX_VALUE;
public class Solution {
public int maxPoints(Point[] points) {
if(points.length<1)
return 0;
int ret = 1;
Map<Double, Integer> map;
for(int i=0;i<points.length-1;i++){
map=new HashMap<Double, Integer>();
int dup=1;
map.put(Double.MAX_VALUE, 0);
for(int j=i+1;j<points.length;j++){
if(points[i].x==points[j].x&&points[i].y==points[j].y){
dup++;
}else if(points[i].x==points[j].x){
map.put(Double.MAX_VALUE, map.get(Double.MAX_VALUE)+1);
}else if(points[i].y==points[j].y){
if(!map.containsKey(0.0))
map.put(0.0, 1);
else
map.put(0.0, map.get(0.0)+1);
}else {
double k = 1.0*(points[i].y-points[j].y)/(points[i].x-points[j].x);
if(!map.containsKey(k))
map.put(k, 1);
else
map.put(k, map.get(k)+1);
}
}
for(double f : map.keySet()){
int tmp=map.get(f)+dup;
if(tmp>ret)
ret=tmp;
}
}
return ret;
}
}