问题描述
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
求二维平面上n个点中,最多共线的点数。
Input: [[1,1],[2,2],[3,3]]
Output: 3
Explanation:
^
|
| o
| o
| o
+------------->
0 1 2 3 4
Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Explanation:
^
|
| o
| o o
| o
| o o
+------------------->
0 1 2 3 4 5 6
解题思路
方法一
- 只有0,1,2个点时,分别返回0,1,2
- 双层遍历,外层是遍历起点,内层是遍历终点,有以下三层情况:
- 若终点跟起点一样或垂直,分别统计重复(chongfu = 0;)/和垂直(chuizhi = 1;)的点数量
- 否则就存在斜率,则计算斜率k,统计斜率相同的点数量
- 每一个遍历的起点共线最多的点数:max(最多斜率k的点数量, 垂直的点数量) + 重复的点数量
注意:
避免使用double类型来计算斜率的除法,因为double表示的双精度小数在有的系统里不一定准确,为了更加精确无误,我们不做除法,而是把除数和被除数都保存下来分别除以它们的最大公约数,然后放在Map<Map<Integer, Integer>, Integer>里。
public static int maxPoints(Point[] points) {
if (points.length <= 2) return points.length;
int max = 0;
for (int i = 0; i < points.length - 1; i++) {
Map<Map<Integer, Integer>, Integer> map = new HashMap<>();
int chongfu = 0;
int chuizhi = 1;
for (int j = i + 1; j < points.length; j++) {
if (points[i].x == points[j].x) {
if (points[i].y == points[j].y) {
//重复的点
chongfu++;
continue;
} else {
//垂直的点
chuizhi++;
continue;
}
} else {
int dy = points[i].y - points[j].y;
int dx = points[i].x - points[j].x;
int d = gcd(dy, dx);
Map<Integer, Integer> m = new HashMap<>();
m.put(dx / d, dy / d);
map.put(m, map.getOrDefault(m, 1) + 1);
}
}
Integer max_k = 0;
for (Integer value : map.values()) {
max_k = Math.max(value, max_k);
}
max = Math.max(Math.max(max_k, chuizhi) + chongfu, max);
}
return max;
}
public static int gcd(int a, int b) {
return (b == 0) ? a : gcd(b, a % b);
}