There is sorted arrays A and B of size m and N respectively. Find The median of the sorted arrays. The overall run time complexity should be O (log (m+n)).
The question is to find the median of two rows of arrays, and more generally, to ask for the number of the first k of the two rows of arrays.
I think of the solution there is a first with a merge sort of two array to sort out an array of arrays, in the traversal to find the number k to, but the complexity of the algorithm is O (NLOGN), obviously does not meet the requirements of the topic.
Refer to the solution in http://blog.csdn.net/zxzxy1988/article/details/8587244:
Assume that a, B, two array elements are larger than K/2. Can compare A[K/2] and B[K/2]
(1) A[K/2-1] < b[k/2-1] At this point can be judged A[0]~A[K/2] than the final median to find smaller, you can remove this part of the element.
(2) A[K/2-1] > b[k/2-1] At this point can be judged B[0]~B[K/2] than the final median to find smaller, you can remove this part of the element.
(3) A[K/2-1] = b[k/2-1] At this time to determine the median to find is a[k/2-1]orb[k/2-1].
Using the above conclusions, the boundary condition is also considered.
The implementation code is as follows
Class Solution {public: double findmediansortedarrays (int a[], int m, int. b[], int n) {int total = m + n;if (& 0x1) {return findkth (A, m, B, N, TOTAL/2 + 1);} Else{return (Findkth (A, m, B, N, TOTAL/2) +findkth (A, M, B,n, TOTAL/2 + 1))/2;}} Double findkth (int a[], int m, int b[], int n, int k) {if (M > N) return findkth (b, N, A, M, k); if (M = = 0) return b[k- 1];if (k <= 1) return min (a[0], b[0]), int idxa = min (K/2, m); int idxb = K-idxa;if (A[idxa-1] < b[idxb-1]) {return fi Ndkth (A+IDXA, M-IDXA, B, N, K-IDXA);} else if (B[idxb-1] < A[idxa-1]) {return findkth (A, M, B + IDXB, N-IDXB, K-IDXB);} Elsereturn a[idxa-1]; };
The use of iterations, taking into account the ease of use of the solution:
if (M > N)
Return findkth (b, N, A, M, k);//This sentence results in half of the subsequent discussion, 32 likes
if (M = = 0)
return b[k-1];
if (k <= 1)
return min (a[0], b[0]);
The boundary situation is discussed.
Learn more, anyway, it's a good time, come on.
Leetcode 4 Median of Sorted Array