This algorithm involves an important mathematical conclusion: if a[k/2-1]<b[k/2-1], then a[0]~a[k/2-1] must be in the sequence of the small number of K, can be proved by contradiction.
The more general conclusion is: K=PA+PB, if a[pa-1]<b[pb-1], then a[0]~a[pa-1] must be in the sequence of the small number of K.
The algorithm idea is as follows:
1, assume that a length is m,b length of n,m>n, and vice versa.
2, Split K=PA+PB.
3, if A[PA-1]<B[PB-1], that proves a[0]~a[pa-1] must be in the combined K decimal sequence. So, you can cut off the front PA number of a, recursive, and similarly chop off the B array.
4, the boundary condition of recursion is if m=0, return b[k-1], if k = 1 (Find first number) return min[a[1],b[1]).
C + + code
DoubleFindkth (intA[],intMintB[],intNintk) { //Always assume this m is equal or smaller than n if(M >N)returnfindkth (b, N, A, M, K); if(M = =0) returnB[k-1]; if(k = =1) returnMin (a[0], b[0]); //divide k into parts intpa = min (k/2, m), Pb = K-PA; if(A[pa-1] < B[PB-1]) returnFindkth (A + PA, m-pa, B, N, K-PA); Else if(A[pa-1] > B[PB-1]) returnFindkth (A, m, B + Pb, N-PB, K-pb); Else returnA[PA-1];}classsolution{ Public: DoubleFindmediansortedarrays (intA[],intMintB[],intN) {intTotal = m +N; if(Total &0x1) returnFindkth (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; }};
Java code
Importjava.util.Arrays; Public classKnumber { Public intFindkth (int[] A,intMint[] B,intNintk) {//Suppose M<n if(m>N)returnfindkth (b,n,a,m,k); if(M = = 0) returnB[k-1]; if(k = = 1) returnMath.min (A[0], b[0]); //The K is divided into two parts, the conclusion is that if A[pa-1]<b[k-pa-1] a[pa] in the order Series A and b composed of a new ordered sequence of the first k in the small sequence. intPA = math.min (K/2, m), Pb = K-PA; if(A[pa-1] < b[pb-1]) { int[] tmp =Arrays.copyofrange (A, PA, a.length);//Note that the boundary is a.length not a.length-1,java the operation of the array is less convenient than the C + + pointerreturnFindkth (tmp,m-pa,b,n,k-PA); } Else if(A[pa-1] > B[pb-1]) { int[] tmp =Arrays.copyofrange (b, Pb, B.length); returnFindkth (A, M, TMP, N-PB, K-pb); } Else returnA[pa-1]; } Public intFindmediansortedarrays (int[] A,intMint[] B,intN) {intTotal = m +N; if(total%2==1) { returnFindkth (A, m, B, N, TOTAL/2); } Else return(Findkth (A, m, B, N, TOTAL/2) +findkth (A, m, B, N, total/2+1))/2; } Public Static voidMain (string[] args) {int[] A = {1,4,9}; int[] B = {4,5,6}; Knumber kn=NewKnumber (); System.out.println (Kn.findmediansortedarrays (A,3, B, 3)); }}
Two ordered sequences are combined into the median of a new ordered sequence, and the K decimal is obtained.