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

前端 未结 3 396
长发绾君心
长发绾君心 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 14:02

    Note that in 1-D the point that minimizes the sum of distances to all the points is the median.

    In 2-D the problem can be solved in O(n log n) as follows:

    Create a sorted array of x-coordinates and for each element in the array compute the "horizontal" cost of choosing that coordinate. The horizontal cost of an element is the sum of distances to all the points projected onto the X-axis. This can be computed in linear time by scanning the array twice (once from left to right and once in the reverse direction). Similarly create a sorted array of y-coordinates and for each element in the array compute the "vertical" cost of choosing that coordinate.

    Now for each point in the original array, we can compute the total cost to all other points in O(1) time by adding the horizontal and vertical costs. So we can compute the optimal point in O(n). Thus the total running time is O(n log n).

提交回复
热议问题