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