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)).
Ideas:
Difficult, know to divide the algorithm, but do not know how to use. Had to look at the answer.
The basic idea is if the median is the number of K, a[i] If the median, then a[i] is greater than the number of I, but also greater than k-i-1 numbers and b[k-i-2] contrast. But if the median is not in a, my brain is dizzy. Here is the big God code, I still do not understand.
classSolution { Public: DoubleFindmediansortedarrays (intA[],intMintB[],intN) {//The following call was to make sure Len (A) <= len (B). //Yes, it calls itself, but at the most once, shouldn ' t is//consider a recursive solution if(M >N)returnfindmediansortedarrays (B, N, A, M); DoubleAns =0; //Now , do binary search intK = (n + M-1) /2; intL =0, r = min (k, m);//R is N, not n-1, the is important!! while(L <r) {intMidA = (L + r)/2; intMidB = k-MidA; if(A[mida] <B[midb]) L= MidA +1; ElseR=MidA; } //After binary search, we almost get the median because it must be between//these 4 numbers:a[l-1], a[l], b[k-l], and b[k-l+1]//if (n+m) is odd, the median is the larger one between A[L-1] and B[k-l]. //And There is some corner cases we need to take care of. intA = max (L >0? A[l-1] : -(1<< -), K-L >=0? B[K-L]:-(1<< -)); if(((n + m) &1) ==1) return(Double) A; //if (n+m) is even, the median can being calculated by//median = (max (a[l-1], b[k-l]) + min (a[l], b[k-l+1])/2.0//Also, there is some corner cases to take care of. intb = min (L < m?) A[l]: (1<< -), K-L +1< n? B[k-l +1] : (1<< -)); return(A + B)/2.0; }};
"Leetcode" Median of the Sorted Arrays (hard) ★!!