Given list of 2d points, find the point closest to all other points

前端 未结 3 395
长发绾君心
长发绾君心 2020-12-30 13:28
Input: list of 2d points (x,y) where x and y are integers.

Distance: distance is defined as the Manhattan distance. 
    ie:
    def dist(p1,p2) 
         return ab         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-30 13:55

    Starting from your initial algortihm, there is an optimization possible:

    minDist=inf
    bestPoint = null
    for p1 in points:
        dist = 0
        for p2 in points:
            dist+=distance(p1,p2)
            //This will weed out bad points rather fast
            if dist>=minDist then continue(p1)
        /*
        //Unnecessary because of new line above
        minDist = min(dist,minDist)
        bestPoint = argmin(p1, bestPoint)
        */
        bestPoint = p1
    

    The idea is, to throw away outliers as fast as possible. This can be improved more:

    • start p1 loop with a heuristic "inner" point (This creates a good minDist first, so worse points get thrown away faster)
    • start p2 loop with heuristic "outer" points (This makes dist rise fast, possibly triggering the exit condition faster

    If you trade size for speed, you can go another route:

    //assumes points are numbered 0..n
    dist[]=int[n+1]; //initialized to 0
    for (i=0;i

    which needs more space for the dist array, but calculates each distance only once. This has the advantage to be better suited to a "get the N best points" sort of problem and for calculation-intensive metrices. I suspect it would bring nothing for the manhattan metric, on an x86 or x64 architecture though: The memory access would heavily dominate the calculation.

提交回复
热议问题