题目如下:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
分析如下:
思路比较直接,对其中某一个点i, 找到点i和剩下的所有n - 1个点构成的斜率。如果在这n - 1个斜率中,能够找到这样一个值,这个出现次数最多,那么就可以认为,取得这些值的点就是能够找到的可以和i在同一个直线上的所有点。
把上面的事情,对所有的点都做一遍,这样就能找到一个最大的点集合,在同一个直线上。
所以用一个hash来统计, key = 斜率, value = 能够和i点取得key的其他点。
坑在,由于用了Float作为key,所以Float里面对0的表达方式有 - 0.0 和0.0两种,所以就造成了两个为0的斜率直线被认为斜率不等。
解决方式比较巧妙,给所有斜率加上0.0即可。
我的代码:
//ERROR: Input: [[2,3],[3,3],[-5,3]] Output : 2 Expected : 3 (slope = -0.0, vs slop = 0.0 are incorrectly viewed as different)
public class Solution {
public int maxPoints(Point[] points) {
if (points == null) {
return 0;
}
if (points.length <= 2) {
return points.length;
}
int global = 0;
for (int i = 0; i < points.length; ++i) {
Map<Double, Integer> map = new HashMap<Double, Integer> ();
double slope = 0.0;
int samePoint = 0;
int verticalPoint = 0;
int local = 1;
for (int j = i + 1; j < points.length; ++j) {
if (points[i].x == points[j].x && points[i].y == points[j].y) {
++samePoint;
} else{
if (points[i].x == points[j].x) {
++verticalPoint;
} else {
//ERROR5: 加上0.0是因为Double representaion会把0.0和-0.0看成不同的数,所以加上0.0来消除这个问题
slope = 0.0 + (points[i].y - points[j].y) * 1.0 / (points[i].x - points[j].x);
if (!map.containsKey(slope)) {
map.put(slope, 2);
} else {
map.put(slope, map.get(slope) + 1);
}
local = Math.max(local, map.get(slope));
}
}
}
local = Math.max(samePoint + 1 + verticalPoint , samePoint + local);
global = Math.max(local, global);
}
return global;
}
}