Given sorted Arrays A, B of size M and N respectively. Find the k-th smallest element in the union of A and B. You can assume that there is no duplicate elements.
O (lg m + LG N) Solution:
1. Maintaining the invariant
i + j = k-1,
2. If Bj-1 < AI < Bj, then AI must is the k-th smallest,
Or else if Ai-1 < BJ < Ai, then Bj must is the k-th smallest.
Code
intFindkthsmallest (intA[],intMintB[],intNintk) {Assert (A&& m >=0&& B && N >=0&& k >0&& k <= m+N); inti = (int)((Double) m/(m+n) * (K-1)); intj = (K-1) -i; ASSERT (I>=0&& J >=0&& I <= m && J <=N); intAi_1 = ((i = =0) ? int_min:a[i-1]); intBj_1 = ((j = =0) ? int_min:b[j-1]); intAi = ((i = = m)?Int_max:a[i]); intBj = ((j = = N)?Int_max:b[j]); if(Bj_1 < AI && ai <Bj)returnAi; Else if(Ai_1 < BJ && BJ <Ai)returnBj; Assert ((Ai> Bj && ai_1 > Bi) | | (Ai < Bj && AI <bj_1)); if(Ai <Bj)returnFindkthsmallest (a+i+1, m-i-1, B, J, k-i-1); Else returnFindkthsmallest (A, I, b+j+1, n-j-1, k-j-1);}
Find the k-th smallest Element in the Union of the Sorted Arrays