Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
[Note]
这是道数学题,知道怎么判断两点是否在同一直线上就行了, 用一个hashmap存经过i这个点斜率相同的所有点的个数,得到假如经过i这个点的线上最大的点数,两个for循环把所有点都算一遍。有几个java问题要注意。
1,在计算斜率时用double类型,但java中的-0.0和0.0是不相等的,所以要把他们都变成0的方法是加0.0:(0.0)+(double)(points[i].x-points[j].x)/(points[i].y-points[j].y)。
2,如果points中有重复的点,我们是要count进去的,不能当成一个点计算。所以这里加了dup这个变量。
/**
* 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 {
public int maxPoints(Point[] points) {
if(points==null || points.length==0) return 0;
HashMap<Double, Integer> map = new HashMap<Double, Integer>();
int max = 0;
int dup = 0;
for(int i=0; i<points.length; i++){
for(int j = i+1; j<points.length; j++){
// x==x && y==y -> same point.
if(points[i].x==points[j].x && points[i].y==points[j].y){
dup++;
continue;
}
//Note1:计算slope, 转换成double类型
double key = points[i].x==points[j].x ? (double)Integer.MAX_VALUE : (0.0)+(double)(points[i].y-points[j].y)/(points[i].x-points[j].x);
if(map.containsKey(key))
map.put(key, map.get(key)+1);
else
map.put(key, 2);
}
//如果map不为空的话,找出最大点数
for(int cnt : map.values())
max = Math.max(max, dup+cnt);
//如果map不为空肯定是由map更新的max最大,dup+1用来更新points.length==1的情况
max = Math.max(max, dup+1);
map.clear();//map和dup都要清空用于下次计算
dup = 0;
}
return max;
}
}
No comments:
Post a Comment