Problem:
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 4Example 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 6NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
Analysis:
本题直接使用斜率的Map是不能够解决的,会遇到精度问题,需要另外想办法。这时我们可以考虑先将分数进行约分,然后再将其转换成为字符串的形式进行Map,代码如下:
Code:
class Solution {
public int maxPoints(int[][] points) {
if(points == null) {
return 0;
} else if(points.length <= 2) {
return points.length;
}
int solution = 0;
for(int i = 0; i < points.length; i++) {
Map<String, Integer> temp = new HashMap<String, Integer>();
int dups = 0;
for(int j = i + 1; j < points.length; j++) {
int x = points[j][0] - points[i][0], y = points[j][1] - points[i][1];
if(x == 0 && y == 0) {
dups++;
continue;
}
int gcd = Gcd(x, y);
x /= gcd;
y /= gcd;
String slope = y + "/" + x;
//System.out.println("[log]: (" + i + ", " + j + ") " + slope);
temp.put(slope, temp.getOrDefault(slope, 0) + 1);
}
int linesMax = 0;
for(int value : temp.values()) {
linesMax = Math.max(linesMax, value);
}
solution = Math.max(solution, 1 + linesMax + dups);
}
return solution;
}
private int Gcd(int a, int b) {
while(b != 0) {
int temp = b;
b = a%b;
a = temp;
}
return a;
}
}