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

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

    If you know the index of the median, which should just be ceil(array.length/2) maybe, then it just should be a process of listing out n(x-k), n(x-k+1), ... , n(x), n(x+1), n(x+2), ... n(x+k) where n is the array, x is the index of the median, and k is the number of neighbours you need.(maybe k/2, if you want total k, not k each side)

提交回复
热议问题