Problem Summary
Given two sorted arrays A and B of size m and n respectively, find the median of the two sorted arrays.
Solution
Apparently, we can merge A and B to get a new sorted array C. Then the answer is the median of C.
The time and space complexities are both O(M+N), so let us think about better solutions.
Suppose M+N is odd, then finding the median of C is actually finding the ((M+N+1)/2)th number of C. So we need a way to find the kth number of C in less than linear time, which leads us to think about algorithms with O(log(M+N)) time complexity, such as binary search.
The point of binary search is to cut the search range by half each time, I think. But can we do the same thing in this problem? To answer this question, let us look at A[k/2-1] and B[k/2-1], which we use M1 and M2 to denote respectively.
In array A, there are k/2-1 numbers smaller than M1, and m-k/2 numbers greater than it. The situation is similar for B and M2. So, if M1 and M2 are equal, there are exactly k-1 numbers in C smaller or equal to M1. Thus M1 is the kth number of C. If M1 < M2, there are less than k-2 numbers in C smaller than M1; therefore, we know M1 and any number smaller than it are not the target we want. So it is safe for us to throw the first k/2 numbers of A out of consideration. The approach is similar when M1 > M2.
Code
|
|