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 shoshould be O (log (m + n )).
A very classic problem. If you look for the median directly, that is, the even number convention is rounded down, and the odd number is the strict median, this question can be calculated by comparing the mid of each array.
However, if the demand for this problem is changed to an even number, the median is the average of the two arrays rounded down and rounded up, so the question is converted to the findkth implementation of the two ordered arrays ~
1st (18 tries)
class Solution {public: double findMedianSortedArrays(int A[], int m, int B[], int n) { if(m > n) return findMedianSortedArrays(B,n,A,m); if((m+n)%2 == 0) return (findkth(A,m,B,n,(m+n)/2) + findkth(A,m,B,n,(m+n)/2+1))/2; else return findkth(A,m,B,n,(m+n)/2+1); } double findkth(int A[],int m,int B[],int n,int k) { if(m <= 0) return B[k-1]; if(n <= 0) return A[k-1]; if(k <= 1) return min(A[0],B[0]); int qa = min(m,k/2); int qb = k - qa; if(A[qa - 1] < B[qb - 1]) { return findkth(A+qa,m-qa,B,n,k-qa); } else if(A[qa - 1] > B[qb - 1]) { return findkth(A,m,B+qb,n-qb,k-qb); } else return A[qa - 1]; }};
2nd (5 tries)
Class solution {public: Double findmediansortedarrays (int A [], int M, int B [], int N) {// odd if (m + n) % 2) {return findk (a, m, B, n, (m + n)/2 + 1);} // even else {return (findk (a, m, B, n, (m + n)/2) + findk (a, m, B, n, (m + n)/2 + 1)/2 ;}} // find two sorted array K num ~ Double findk (int A [], int M, int B [], int N, int K) {return findk (A, 0, S-1, B, 0, n-1, k);} double findk (int A [], int astart, int aend, int B [], int bstart, int bend, int K) {// Step 1 If (astart> aend) {return B [bstart + k-1];} If (bstart> bend) {return a [astart + k-1];} // Step 2 // step 3 int amid = astart + (aend-astart)/2; int bmid = bstart + (bend-bstart)/2; int halflen = amid-astart + 1 + bmid-bstart + 1; if (a [amid] <B [bmid]) {If (halflen> K) {return findk (A, astart, aend, B, bstart, bmid-1, k);} else {return findk (A, amid + 1, aend, B, bstart, bend, K-(amid-astart + 1) ;}} else {If (halflen> K) {return findk (A, astart, amid-1, B, bstart, bend, k);} else {return findk (A, astart, aend, B, bmid + 1, bend, k-(bmid-bstart + 1 ));}}}};