Title Address: https://leetcode.com/problems/median-of-two-sorted-arrays/
Topic Analysis: See the topic of the first idea is to use two points to find, but deep down to find the use of two points to find a lot of boundaries and details of the processing is very troublesome, back to the second, the use of divided treatment method. If the length and number of two arrays is an even number, the average of the median two numbers of the two arrays is obtained, and if the length and cardinality are two array intermediate numbers. This translates into a more general question-the number of K for two sorted arrays, the first m for two sorted arrays, the top N of the second array, the guaranteed m+n=k, and the nth size of the first array of M and the second array, If the first array is large, it removes the m+1 element from the first array, and the first n elements of the second array, and finds the K-M elements of the remaining elements.
Topic Answer:
Public classSolution { Public DoubleFindmediansortedarrays (intA[],intb[]) { if(A.length = = 0 | | A = =NULL){ if(B.length = = 0 | | B = =NULL){ return0; }Else{ return(b[b.length/2]+b[(B.LENGTH-1)/2])/2.0; } }Else{ if(B.length = = 0 | | B = =NULL){ return(a[a.length/2]+a[(A.LENGTH-1)/2])/2.0; }Else{ if((a.length + b.length)%2 = = 0){ return(Findkth (A, B, (A.length + b.length)/2,0,a.length-1,0,b.length-1) +findkth (A, B, (A.length+ b.length)/2-1,0,a.length-1,0,b.length-1)/2.0; }Else{ returnFindkth (A, B, (A.length + b.length)/2,0,a.length-1,0,b.length-1); } } } } Private intFindkth (int[] A,int[] B,intKintAstart,intAend,intbstart,intBEnd) { intALen = Aend-astart + 1; intBlen = Bend-bstart + 1; if(ALen = = 0){ returnB[bstart +K]; } if(Blen = = 0){ returnA[astart +K]; } if(k = = 0) returnA[astart] < B[bstart]?A[astart]: B[bstart]; intAMid = alen*k/(alen+Blen); intBmid = k-amid-1; AMid+=Astart; Bmid+=bstart; if(A[amid] = =B[bmid]) { returnA[amid]; }Else if(A[amid] >B[bmid]) {k= K-(Bmid-bstart + 1); Aend=AMid; Bstart= Bmid + 1; }Else{k= K-(Amid-astart + 1); BEnd=Bmid; Astart= AMid + 1; } returnfindkth (a,b,k,astart,aend,bstart,bend); }}
Leetcode Median of the Sorted Arrays