Calculate the merged median from two ordered arrays.

Source: Internet
Author: User

If the efficiency reaches log2n, the first thing that comes to mind is binary search. First, consider the case where two sorted arrays have the same length, we found A [n/2] and B [n/2] to compare them. If they are equal, then our search is over, because the answer has found A [n/2], it must be the median after sorting.

If we find that B [n/2]> A [n/2], it indicates that this number should be in the sequence A [n/2]> A [n, or B [1]-B [n/4. Successfully solved the problem by finding the merged array in the sorted array A [n/2]-A [n] and B [0]-B [n/2 ]. median, obviously recursion is a good choice.

Similarly, what if B [n/2] <A [n/2? It is clearly found in A [0]-A [n/2] and B [n/2]-B [n. Www.2cto.com

When will this recursion converge? Of course, a case is an equal value. If it does not appear, it will end when n = 1.

In the same way, we can compare the two arrays without losing its universality. We assume that array B is A little better than the group leader. The length of A is n, and that of B is m. When comparing A [n/2] and B [m/2. Similarly, we can discuss it in several situations:

① If A [n/2] = B [m/2], it is clear that our discussion is over. A [n/2] is already the median, which is irrelevant to their respective lengths being odd or even.

② If A [n/2] <B [m/2], then we can know that this median is definitely not [A [0], A [n/2]) this interval is not included in [B [m/2], B [m. At this time, we cannot impulsively throw [A [0], A [n/2]), [B [m/2], and B [m. We only need to discard [B [m-n/2], B [m] and [A [0], A [n/2. (In red box ), in this way, we have successfully converted our problem into an array with the length of A [n/2]-> A [n] and B [1]-B [m-n/2] Find the median in the array with the length of m-n/2. The complexity of the problem can be reduced.

③ Only A [n/2]> B [m/2] is left. Similar to B, we can discard A [n/2]-> A [n] and B [1]-> B [n/2] and continue recursion.

From he Hao column programmer interview 500
 

Related Article

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.