【发布时间】:2025-11-23 04:00:01
【问题描述】:
这个“给定二维平面上的 n 个点,找出位于同一直线上的最大点数。” 来自 leetcode.com 的问题 我正在尝试解决它,但我无法通过所有测试 案例。
我正在尝试做的是:- 我正在使用一个哈希图,其键是角度 b/w 我通过斜率的 tan 倒数得到的点,并且我存储每个斜率的值最初是该点的出现次数,然后递增它。
我正在使用另一个哈希图来计算点的出现次数。
对于 (0,0),(1,0) 之类的点,我没有得到正确答案,它们应该返回 2,但它返回 1。
我错过了什么?
我的代码是:
public class MaxPointsINLine {
int max = 0;
int same;
public int maxPoints(Point[] points) {
int max = 0;
Map<Double, Integer> map = new HashMap<Double, Integer>();
Map<Point, Integer> pointmap = new HashMap<Point, Integer>();
for(Point point: points)
{
if(!pointmap.containsKey(point))
{
pointmap.put(point, 1);
}
else
{
pointmap.put(point, pointmap.get(point)+1);
}
}
if (points.length >= 2) {
for (int i = 0; i < points.length; i++) {
for (int j = i ; j < points.length; j++) {
double dx = points[j].x - points[i].x;
double dy = points[j].y - points[i].y;
double slope = Math.atan(dy / dx);
if (!map.containsKey(slope)) {
map.put(slope, pointmap.get(points[j]));
} else
map.put(slope, map.get(slope) + 1);
}
}
for (Double key : map.keySet()) {
if (map.get(key) > max) {
max = map.get(key);
}
}
return max;
} else if (points.length != 0) {
return 1;
} else {
return 0;
}
}
public static void main(String[] args) {
Point point1 = new Point(0,0);
Point point2 = new Point(0,0);
//Point point3 = new Point(2,2);
MaxPointsINLine maxpoint = new MaxPointsINLine();
Point[] points = { point1, point2};
System.out.println(maxpoint.maxPoints(points));
}
}
class Point {
int x;
int y;
Point() {
x = 0;
y = 0;
}
Point(int a, int b) {
x = a;
y = b;
}
@Override
public boolean equals(Object obj) {
Point that = (Point)obj;
if (that.x == this.x && that.y == this.y)
return true;
else
return false;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return 1;
}
}
【问题讨论】:
-
你填充了
pointmap,但你从不使用它。你的意思是把它合并到算法中吗? -
@Chris Culter 对不起,我正在使用点图 -if (!map.containsKey(slope)) {map.put(slope, pointmap.get(points[j]));} 如果有是像 (0,0)(0,0) 这样的点,它会将值 2 放入地图中。
-
我不知道最初的问题,但我非常不愿意使用 atan 并为此依赖浮点比较。它可能会导致意想不到的答案(从数学的角度来看)。
-
看到这个问题可能对你有帮助*.com/questions/4179581/…
-
使用
Double作为查找键是非常可疑的如果您希望通过计算找到相同的Double(考虑浮点不准确!) .此外,任何依赖于 slope 的 几何计算与点 都被视为失败:当点具有相同的 x 坐标时(或者在您的情况下:x 坐标0),您将遇到Infinity和NaN。此外,即使直线不通过原点,也有一些点位于同一直线上。所以我认为这种方法总体上是有缺陷的(但我也可能是错的......)