149. Max Points on a Line
09/16/2021
Last updated
09/16/2021
Last updated
class Solution {
public int maxPoints(int[][] points) {
if (points.length == 1) {
return 1;
}
int ret = 0;
for (int i = 0; i < points.length; ++i) {
int[] p1 = points[i];
Map<Double, Integer> map = new HashMap<>();
// 只需要考虑后面出现的点,因为前面的点之前已经考虑过
for (int j = i + 1; j < points.length; ++j) {
int[] p2 = points[j];
int dx = p2[0] - p1[0];
int dy = p2[1] - p1[1];
double ratio = 0;
if (dx == 0) {
ratio = Double.MIN_VALUE;
} else if (dy == 0) {
ratio = 0;
} else {
ratio = (double) dy / dx;
}
map.put(ratio, map.getOrDefault(ratio, 1) + 1);
ret = Math.max(ret, map.get(ratio));
}
}
return ret;
}
}