186. 最多有多少个点在一条直线上
给出二维平面上的n个点,求最多有多少点在同一条直线上。
样例
样例 1:
输入:(1,2),(3,6),(0,0),(1,3).
输出:3
样例 2:
输入:(1,2),(2,3),(3,2).
输出:2
注意事项
x点和y点的坐标值在-1000~1000之间
由于通过斜率来判断共线需要用到除法,而用double表示的双精度小数在有的系统里不一定准确,为了更加精确无误的计算共线,我们应当避免除法,从而避免无线不循环小数的出现,那么怎么办呢,我们把除数和被除数都保存下来,不做除法,但是我们要让这两数分别除以它们的最大公约数,这样例如8和4,4和2,2和1,这三组商相同的数就都会存到一个映射里面,同样也能实现我们的目标,而求GCD的函数如果用递归来写那么一行就搞定了。
/**
* 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 {
/**
* @param points: an array of point
* @return: An integer
*/
public int maxPoints(Point[] points) {
// Write your code here
if (points == null) {
return 0;
}
int ans = 0;
for (int i = 0; i < points.length; i++) {
Map<String, Integer> slope = new HashMap<>();
int maxPoints = 0, overlap = 0, 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) {
overlap++;
} else {
vertical++;
}
continue;
}
int dx = points[i].x - points[j].x;
int dy = points[i].y - points[j].y;
int tmp = gcd(dx, dy);
dx /= tmp;
dy /= tmp;
String k = dy + "/" + dx;
if (!slope.containsKey(k)) {
slope.put(k, 0);
}
slope.put(k, slope.get(k) + 1);
maxPoints = Math.max(maxPoints, slope.get(k));
}
maxPoints = Math.max(maxPoints, vertical);
ans = Math.max(ans, maxPoints + overlap + 1);
}
return ans;
}
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
}