Java - 快速找到一组点中的四个"extreme corners"?



假设给定一组随机坐标的x和y边界(称为边界A和B),例如x<=10,y<=10.找到最接近(0,0)、(A,0)、(A,B)、(0,B)的四个点的最快方法是什么?如果速度更快的话,这些点可以从最小到最大排序。这就是我目前所拥有的,但我觉得这可以加快:

 private void quadrilateral(){
    NW = null;
    NE = null;
    SE = null;
    SW = null;
    Point NWbound = new Point(0,B);
    Point NEbound = new Point(A,B);
    Point SEbound = new Point(A, 0);
    Point SWbound = new Point(0,0);
    for (Point p : points){
        if (NW == null || p.distance(NWbound) < NW.distance(NWbound)){
            NW = p;
        }
        if (NE == null || p.distance(NEbound) < NE.distance(NEbound)){
            NE = p;
        }
        if (SE == null || p.distance(SEbound) < SE.distance(SEbound)){
            SE = p;
        }
        if (SW == null || p.distance(SWbound) < SW.distance(SWbound)){
            SW = p;
        }
    }

}

我还没有能够使用排序列表,我甚至不确定排序列表是否有帮助。

要使其更快,请使用p.distanceSq()而不是p.distance()。此外,请保存四个最接近的距离平方值中的每一个,这样您就不必在每次迭代中重复计算它们。

最新更新