【发布时间】:2015-04-28 23:14:02
【问题描述】:
给定二维平面上的 n 个点,找出位于同一直线上的最大点数。
这个编程谜题取自 Leetcode 上的here
以下是我尝试解决的方法。
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
public int maxPoints(Point[] points) {
if (points.length==0) return 0;
Map[] maps = new Map[points.length];
for (int i=0; i<points.length; i++) {
Map<Double, Integer> map = new HashMap<Double, Integer>();
maps[i] = map;
}
//count the points with the same coordinates
int [] identical = new int[points.length];
//count the points that form a vertical line against the x-axis
int [] vertical = new int[points.length];
for (int i=0; i<points.length; i++) {
for (int j=i+1; j<points.length; j++) {
Point A = points[i];
Point B = points[j];
if (A.x != B.x) {
double slope = (A.y-B.y)/(A.x-B.x);
if (maps[i].containsKey(slope)) {
maps[i].put(slope, (int)maps[i].get(slope)+1);
} else {
maps[i].put(slope, 1);
}
if (maps[j].containsKey(slope)) {
maps[j].put(slope, (int)maps[j].get(slope)+1);
} else {
maps[j].put(slope, 1);
}
} else if (A.y == B.y) {
identical[i]++;
identical[j]++;
} else {
vertical[i]++;
vertical[j]++;
}
}
}
int max = 0;
for (int i=0; i<points.length; i++) {
int maxForCurrentPoint = vertical[i];
for (Object entry : maps[i].entrySet())
{
int num = (int)((Map.Entry)entry).getValue();
if (num > maxForCurrentPoint) {
maxForCurrentPoint = num;
}
}
maxForCurrentPoint += identical[i]+1; //the extra 1 counts for the point itself
if (maxForCurrentPoint > max)
max = maxForCurrentPoint;
}
return max;
}
}
但是,我无法通过测试用例。测试结果如下:
通过了 19 / 27 个测试用例。
输入:[[84,250],[0,0],[1,0],[0,-70],[0,-70],[1,-1],[21,10],[ 42,90],[-42,-230]] 输出:8 预期:6
我的代码逻辑对我来说似乎没问题,但也许我遗漏了一些我不知道的东西?我也对这里使用的哈希表有疑问。有人能解释一下这个问题吗?
【问题讨论】:
标签: java algorithm data-structures hashtable computational-geometry