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

后端 未结 13 1463
别跟我提以往
别跟我提以往 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:04

    Four Steps:

    1. Use Median of medians to locate the median of the array - O(n)
    2. Determine the absolute difference between the median and each element in the array and store them in a new array - O(n)
    3. Use Quickselect or Introselect to pick k smallest elements out of the new array - O(k*n)
    4. Retrieve the k nearest neighbors by indexing the original array - O(k)

    When k is small enough, the overall time complexity becomes O(n).

提交回复
热议问题