Description:
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
Example 2:
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
NOTE:
- input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
题意:给定一组二维平面上的坐标点,找出能构成一条直线的最多的点,即最多有多少个点可以在同一条直线上;
解法:我们知道一条直线的表达式为y=kx+by=kx+by=kx+b,可以得到直线上的任意两个点满足
x1−x2y1−y2=k
\frac{x1-x2}{y1-y2}=k
y1−y2x1−x2=k
因此,遍历坐标上的每个点,统计相同斜率的有多少个点,找出使点最多的那个斜率;为了比较,这里的斜率我们使用分数来存储,并且需要进行约分;
Java
class Solution {
public int maxPoints(int[][] points) {
if (points == null) {
return 0;
}
if (points.length <= 2) {
return points.length;
}
int result = 0;
for (int i = 0; i < points.length; i++) {
int max = 0;
int overlap = 0;
Map<String, Integer> map = new HashMap<>();
for (int j = i + 1; j < points.length; j++) {
int x = points[j][0] - points[i][0];
int y = points[j][1] - points[i][1];
if (x == 0 && y == 0) {
overlap++;
continue;
}
int xyGcd = gcd(x, y);
x /= xyGcd;
y /= xyGcd;
String k = "" + x + y;
map.put(k, map.getOrDefault(k, 0) + 1);
max = Math.max(max, map.get(k));
}
result = Math.max(result, max + 1 + overlap);
}
return result;
}
public int gcd(int x, int y) {
if (y == 0) {
return x;
}
return gcd(y, x % y);
}
}