How to find k nearest neighbors to the median of n distinct numbers in O(n) time?

后端 未结 13 1461
别跟我提以往
别跟我提以往 2021-02-02 16:26

I can use the median of medians selection algorithm to find the median in O(n). Also, I know that after the algorithm is done, all the elements to the left of the median are les

13条回答
  •  北恋
    北恋 (楼主)
    2021-02-02 17:09

    All the answers suggesting to subtract the median from the array would produce incorrect results. This method will find the elements closest in value, not closest in position.

    For example, if the array is 1,2,3,4,5,10,20,30,40. For k=2, the value returned would be (3,4); which is incorrect. The correct output should be (4,10) as they are the nearest neighbor.

    The correct way to find the result would be using the selection algorithm to find upper and lower bound elements. Then by direct comparison find the remaining elements from the list.

提交回复
热议问题