Given
n
points on a 2D plane, find the maximum number of points that lie on the same straight line.
给定一些点的横纵坐标,找出在同一直线上的点的最大数目
不会写,抄答案。
指定某一个点,计算包含该点的所有直线上有多少个点。具体方法是计算剩下的所有点与该指定点的斜率,斜率相同就认为是在同一直线上,注意以下几个问题:
1. 可能会有重合的点,代码中self是为了解决这个问题
2. 可能会有平行于Y轴的直线,ver是为了解决这个问题
3. LeetCode上面有一个很刁钻的用例,(0,0),(94911151,94911150),(94911152,94911151),这三个点并不在意同一条直线上,但是后两个点与第一个点的斜率都是0.9999999894638303,这是由于精度不够造成的,而java中又没有比double更大精度的数,因此取巧,将所有的斜率均扩大10倍,可以AC
class Solution {
public int maxPoints(Point[] points) {
int len = points.length;
if(len == 0)
return 0;
Map<Double, Integer> map = new HashMap<Double, Integer>();
int res = 1;
for(int i = 0; i < len; i++){
Point cur = points[i];
map.clear();
int self = 1, ver = 0;
for(int j = i + 1; j < len; j++){
Point it = points[j];
if(cur.x == it.x && cur.y == it.y)
self++;
else if(cur.x == it.x)
ver++;
else{
double k = (double)(cur.y - it.y) * 10 / (cur.x - it.x);
if(k == -0.0)
k = 0.0;
if(!map.containsKey(k))
map.put(k, 0);
map.put(k, map.get(k) + 1);
}
}
res = Math.max(res, ver + self);
for(double key : map.keySet())
res = Math.max(res, map.get(key) + self);
}
return res;
}
}