这是一道来自leetcode.com的题目:“给定二维平面上的n个点,找到位于同一直线上的最大点数。” 我正在尝试解决它,但我无法通过所有的测试用例。
我的做法是:使用一个哈希表,其键为通过斜率的正切得到的点之间的角度,并且我将每个斜率的值存储在哈希表中。最初,该点的出现次数为1,然后逐渐增加。
我还使用另一个哈希表来计算点的出现次数。
对于像(0,0),(1,0)这样的点,我的代码无法得出正确的答案,应该返回2,但实际上只返回1。
我错在哪里?
我的代码如下:
我的做法是:使用一个哈希表,其键为通过斜率的正切得到的点之间的角度,并且我将每个斜率的值存储在哈希表中。最初,该点的出现次数为1,然后逐渐增加。
我还使用另一个哈希表来计算点的出现次数。
对于像(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 Culter0
)时,您将面临“无穷大”和“NaN”的问题。此外,即使该线未经过原点,也存在在同一条线上的点。因此,我认为该方法总体上是有缺陷的(但我可能也是错的...)。 - Marco13