我正在尋找一種算法來找到最快的方法來找到盒子中的所有點2D(x,y)(盒子由2個點定義:lowerLeft和upperRight)。在一個盒子裏找到第二個點
想象一下,我們在2D空間中有200萬個點。
在那個2D空間中,我創建了一個從2點開始的盒子,一個是左下角,另一個是右上角。 獲取盒子中所有點的最快方法是什麼? 下面是最壞情況下的java測試:循環每個點(200萬!)並確定它是否在盒子內。 我相信,如果點的名單先排序,我們可以變得更快...
您有什麼想法嗎?
public class FindPointsInBox {
public static void main(String[] args) throws Exception {
// List of 2,000,000 points (x,y)
List<Point> allPoints = new ArrayList<Point>();
for(int i=0; i<2000000; i++) {
allPoints.add(new Point(46 - (Math.random()), -74 - (Math.random())));
}
// Box defined by 2 points: lowerLeft and upperRight
List<Point> pointsInBox = new ArrayList<Point>();
Point lowerLeft = new Point(44.91293325430085, -74.25107363281245);
Point upperRight = new Point(45.3289676752705, -72.93820742187495);
Date t1 = new Date();
// TODO: What is the fastest way to find all points contained in box
for(int i=0; i<allPoints.size(); i++) {
if(isPointInBox(allPoints.get(i), lowerLeft, upperRight))
pointsInBox.add(allPoints.get(i));
}
Date t2 = new Date();
System.out.println(pointsInBox.size() + " points in box");
System.out.println(t2.getTime()-t1.getTime() + "ms");
}
private static boolean isPointInBox(Point p, Point lowerLeft, Point upperRight) {
return (
p.getX() >= lowerLeft.getX() &&
p.getX() <= upperRight.getX() &&
p.getY() >= lowerLeft.getY() &&
p.getY() <= upperRight.getY());
}
}
下面的答案表明你需要更清楚一點你的問題:具體來說,*當*你受到時間的限制嗎?如果允許您在添加點數時花費處理時間,但需要快速查詢盒內查詢,那麼Mikhail Vladimirov的預計算思路將有所幫助。然而,如果你的字面意思是隻有200萬分,並且必須儘快找到解決方案,那麼Grigor Gevorgyan是正確的:沒有更快的解決方案。 – jazzbassrob 2013-02-13 13:37:22
對不起,我忘了說明這是t1和t2之間對我來說很重要的時間。添加積分時,我可以花費處理時間。所以像米哈伊爾弗拉基米羅夫所說的Quadtree對我來說是完美的解決方案。 Thansk傢伙! – Robert 2013-02-13 17:02:39