Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
思路是:用两个循环去查看所有情况
same 表示两个点完全重合
sameX 表示两个点有相同的x坐标
public int maxPoints(Point[] points) {
if (points == null || points.length == 0) return 0;
if (points.length <= 2) return points.length;
int res = 0, len = points.length;
for (int i = 0; i < len; i++) {
Point start = points[i];
int same = 1, sameX = 0, max = 0;
Map<String, Integer> hm = new HashMap<>();
for (int j = 0; j < len; j++) {
if (i == j) continue;
Point end = points[j];
if (start.x == end.x && start.y == end.y) same++;
else if (start.x == end.x) sameX++;
else {
String slope = getSlope(start, end);
hm.put(slope, hm.getOrDefault(slope, 0) + 1);
max = Math.max(max, hm.get(slope)); 计算出相同斜率的最大的个数
}
}
max = Math.max(max, sameX) + same; 从相同斜率和有相同X坐标的点选出最大的 加上 点完全重合点的个数
res = Math.max(res, max);
}
return res;
}
private String getSlope(Point p1, Point p2) {
int a = p1.y - p2.y;
int b = p1.x - p2.x;
if (b == 0) return null;
int gcd = a >= b ? gcd(a, b) : gcd(b, a);
a /= gcd;
b /= gcd;
return a + "/" + b;
}
private int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}