Calculate the number of K nearest to the median in an unordered array in the O (n) time.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.