There is sorted arrays nums1 and nums2 of size M and N respectively.
Find The median of the sorted arrays. The overall run time complexity should be O (log (m+n)).
Example 1:
NUMS1 = [1, 3]nums2 = [2]the median is 2.0
Example 2:
NUMS1 = [1, 2]NUMS2 = [3, 4]the median is (2 + 3)/2 = 2.5
==============
Find the median of two arrays,
The definition of the median is clear: the ordered array, array.size=n is an odd number, (n+1)/2 digits; otherwise it is the average of N/2 and (n+1)/2.
========== ideas:
Division of Ideas,
The first step: follow the merge idea to find two in the array of K-large
The second step is to return the median by the method of calculating the median number.
=========
Code implementation,
classSolution { Public: DoubleFindmediansortedarrays (vector<int>& Nums1, vector<int>&nums2) { intLengtha =nums1.size (); intLENGTHB =nums2.size (); intTotal = lengtha+LENGTHB; if(Total &0x1){ returnFind_kth (nums1,nums2,total/2+1); }Else{ return(Find_kth (nums1,nums2,total/2)+find_kth (Nums1,nums2,total/2+1))/2.0; } }Private: intFind_kth (vector<int> &A,vector<int> &b,intk) {std::vector<int>::const_iterator P1 =A.begin (); Std::vector<int>::const_iterator P2 =B.begin (); intm =0; while(P1!=a.end () && p2!=B.end ()) { if(*p1<=*p2 && m== (K-1)){ return*P1; }Else if(*p1>*p2 && m== (K-1)){ return*P2; } if(*p1<=*p2) P1++; ElseP2++; M++; }// while while(p1!=A.end ()) { if(m== (K-1)){ return*P1; } p1++; M++; } while(p2!=B.end ()) { if(m== (K-1)){ return*P2; } P2++; M++; } return-1; }};
4. Median of Sorted Arrays