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

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

    med=Select(A,1,n,n/2)   //finds the median
    
    for i=1 to n
       B[i]=mod(A[i]-med)
    
    q=Select(B,1,n,k) //get the kth smallest difference
    
    j=0
    for i=1 to n
       if B[i]<=q 
         C[j]=A[i] //A[i], the real value should be assigned instead of B[i] which is only the difference between A[i] and median.
           j++
    return C
    

提交回复
热议问题