Asked yesterday, so I immediately thought of a method.
The problem is that given an unordered array, finding the nearest K number to the median requires O (n) complexity.
The idea is as follows:
First, we need to know that the median of unordered Arrays can be obtained within the O (n) time by using linear time selection.
(1) O (n) calculates the median of unordered arrays.
(2) subtract the median from all the numbers in the array and take the absolute value to get a new array. Each number in this array represents its distance from the median. Complexity O (n ).
(3) using the linear time selection method, we can obtain the number of K at O (n) time. At this time, all the numbers on the left of K are smaller than K, and K is the smallest number.
(4) The original number corresponding to the minimum K number is the k Number closest to the median.
This completes the requirements.