【发布时间】:2016-08-21 14:05:58
【问题描述】:
我有以下代码:
public static Location findClosest(Location myPosition, ArrayList<Location> spots) {
double min = Double.MAX_VALUE;
Location closer = null;
for(MyPosition aPosition:spots) {
float dist = Math.abs(aPosition.distanceTo(myPosition));
if(dist < min) {
min = dist;
closer = aPosition;
}
}
return closer;
}
这是一种蛮力 O(N^2) 方法,因为它是从以下函数调用的:
public static Location findClosest(Location myPosition, ArrayList<Places> places) {
Location closer = null;
double min = Double.MAX_VALUE;
for(Places place:places) {
Location currentMin = findClosest(myPosition, places.getSpots());
float dist = Math.abs(currentMin.distanceTo(myPosition));
if(dist < min) {
min = dist;
closer = currentMin;
}
}
return closer;
}
考虑到斑点的大小不是那么大~200 max.
我可以做些什么来改进我的方法?
除了 geohashing,我还有什么其他算法可以提高性能吗?
是否有一些坐标属性可以用来跳过循环的某些部分?
【问题讨论】:
-
你可以使用优先级队列而不是列表,此时你会得到 O(1),我在这里也看到 O(n),除非我错过了什么......
-
我看不到 O(N^2) - 但只能看到线性。无论如何,如果您能够“以某种方式”预处理点,您可以将它们存储在一些空间数据结构中,例如 R-tree、QuadTree、KD-Tree 等......以加快搜索速度。正确的数据结构取决于您使用的维度数量等。例如,请参阅 en.wikipedia.org/wiki/R-tree 或 en.wikipedia.org/wiki/Quadtree
-
@Palcente:如何使用优先队列?我不明白
-
@convexHull:你是对的。它不是 O(N),因为我从另一个我省略提及的循环中调用了这个函数。我会更新OP。我不知道预处理可能是什么
-
在插入过程中保持优先级队列中的顺序。因此,您的
findClosest()方法只需要从spots中提取第一项,就可以保证它是最近的位置。
标签: java android algorithm geolocation coordinates