Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Example 1:
Input: [[1,1],[2,2],[3,3]]
Output: 3
Explanation:
^
|
| o
| o
| o
+------------->
0 1 2 3 4
给出一系列点的坐标,输出在一条线上最多的点数
思路:
在一条线上说明斜率是一样的,每选中一个点i,看剩下的点(i+1到最后)与它构成的线的斜率,如果斜率一样,这条线上的点数就+1
还有一种情况,就是重复的点,几个点在同一个位置上
同一条线上的点数就是上述两种情况点的和
用一个HashMap保存斜率和这个斜率的次数,每选一个新的点i就要用一个新的HashMap,不然会有重复的case,计算出相同的斜率,这个斜率的次数就+1
斜率,如果直接用两个数除,由于计算机中小数不精确,所以要避免除法,可以用另一个HashMap保存<dx, dy>,或者用一个String保存dx/dy
而且dx和dy要除以它们的最大公约数
因此涉及求最大公约数的问题
gcd(a, b) = return (b == 0) ? a : gcd(b, a%b);
可以证明(a,b)的最大公约数 = (b, a%b)的最大公约数
用HashMap保存斜率的<dx, dy>时间复杂度稍微高一些,所以用String
//13ms
public int maxPoints(int[][] points) {
if (points == null) {
return 0;
}
if (points.length <= 2) {
return points.length;
}
int sameLine = 0;
int samePoint = 1;
int res = 0;
for (int i = 0; i < points.length; i++) {
HashMap<String, Integer> count = new HashMap<>();
int[] x = points[i];
samePoint = 1;
sameLine = 0;
for (int j = i + 1; j < points.length; j++) {
int[] y = points[j];
int dx = x[0] - y[0];
int dy = x[1] - y[1];
int d = gcd(dx, dy);
if (dx == 0 && dy == 0) { //same points..
samePoint ++;
continue;
}
String slope = "" + (dy/d) + "/" + (dx/d);
count.put(slope, count.getOrDefault(slope, 0) + 1);
sameLine = Math.max(sameLine, count.get(slope));
}
res = Math.max(res, sameLine + samePoint);
}
return res;
}
//greatest common divisor..
public int gcd(int m, int n) {
return (n == 0) ? m : gcd(n, m % n);
}