Median of Two Sorted Arrays
There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time
complexity should be O(log (m+n)).
Idea: The trivial solution is to consolidate these two sorted arrays and then find the median, then the time complexity is O(m+n) and we also need the extra space. Is there any way to utilize the properties of these two arrays: "sorted"? Tje answer is YES. A helper function will be created: findKthFromTwoSortedArrays(int A[], int starta, int enda, int B[], int startb, int endb, int k) ---- to find the k-th element from two sorted arrays.
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int mid = m+n;
if( mid%2 == 0) {
return (findKthFromTwoSortedArrays(A, 0, m, B, 0, n, mid/2) +
findKthFromTwoSortedArrays(A, 0, m, B, 0, n, mid/2+1))/2.0;
}
else {
return findKthFromTwoSortedArrays(A, 0, m, B, 0, n, mid/2+1);
}
}
double findKthFromTwoSortedArrays(int A[], int starta, int enda,
int B[], int startb, int endb, int k) {
if(starta == enda) {
return B[startb+k-1];
}
if(startb == endb) {
return A[starta+k-1];
}
if(k == 1) return std::min(A[starta], B[startb]);
int mid = k/2;
int min_len = std::min(enda-starta, endb-startb);
mid = std::min(mid, min_len);
if(A[starta+mid-1] > B[startb+mid-1]) {
return findKthFromTwoSortedArrays(A, starta, enda,
B, startb+mid, endb, k-mid);
}
else {
return findKthFromTwoSortedArrays(A, starta+mid, enda,
B, startb, endb, k-mid);
}
}
};