149. 直线上最多的点数
给你一个数组 points ,其中 points[i] = [xi, yi] 表示 X-Y 平面上的一个点。求最多有多少个点在同一条直线上。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-points-on-a-line
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
class Solution {
private int gcd(int a, int b) {
while (b != 0) {
int t = a % b;
a = b;
b = t;
}
return a;
}
public int maxPoints(int[][] points) {
if (points == null || points.length == 0 || points[0].length == 0) {
return 0;
}
int ret = 0;
for (int i = 0; i < points.length; ++i) {
Map<Line, Integer> map = new HashMap<>();
int same = 1;
int max = 0;
for (int j = i + 1; j < points.length; ++j) {
if (points[i][0] == points[j][0] && points[i][1] == points[j][1]) {
same++;
} else if (points[i][0] == points[j][0]) {
Line line = new Line(0, 1);
Integer cnt = map.getOrDefault(line, 0);
map.put(line, cnt + 1);
max = Math.max(max, cnt + 1);
} else if (points[i][1] == points[j][1]) {
Line line = new Line(1, 0);
Integer cnt = map.getOrDefault(line, 0);
map.put(line, cnt + 1);
max = Math.max(max, cnt + 1);
} else {
int x = points[i][0] - points[j][0];
int y = points[i][1] - points[j][1];
int gcd = gcd(x, y);
Line line = new Line(x / gcd, y / gcd);
Integer cnt = map.getOrDefault(line, 0);
map.put(line, cnt + 1);
max = Math.max(max, cnt + 1);
}
}
ret = Math.max(ret, same + max);
}
return ret;
}
}
class Line {
int x;
int y;
public Line(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Line line = (Line) o;
return x == line.x &&
y == line.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号