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

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

    You can solve your problem like that:

    You can find the median in O(n), w.g. using the O(n) nth_element algorithm.

    You loop through all elements substutiting each with a pair:

    the absolute difference to the median, element's value. 
    

    Once more you do nth_element with n = k. after applying this algorithm you are guaranteed to have the k smallest elements in absolute difference first in the new array. You take their indices and DONE!

提交回复
热议问题