Optimal Solution O (log (min (m, n)))
/ * * Before thinking combined with an ordered array made O ((m + n + 1 ) / 2), now try to O (log (min (m, n))) The basic idea is: Find than by binary the median obtain a corresponding array of small (assuming the presence of a last bounds of routine) assume respectively n1, n2, must n1 <= n2, two assumptions may median finally found that m1, m2 number (or assume present) when then binary search nums1, the initial value left = 0, right = n1; m1 is there [0, n1], m2 has a [k-n1, n1] ( k-n1> = 0 necessarily holds) and n1 <= n2, so certainly m2 between [0, n2], and therefore does not need to traverse the small array of things to worry about cross-border, just at the end of treatment 0 and n1, n2 of special circumstances; ** * / class Solution { public : Double findMedianSortedArrays (Vector < int > & nums1, Vector < int > & nums2) { // first detects whether the first array is small, large arrays after const int N1 = nums1.size (); const int N2 =nums2.size(); if(n1>n2) return findMedianSortedArrays(nums2,nums1); int m1,m2; int left=0,right=n1,k=(n1+n2+1)/2; //二分查找m1,m2(假设存在) while(left<right){ m1=left+(right-left)/2; m2=k-m1; if(nums1[m1]<nums2[m2-1]) left=m1+1; else right=m1; } M1 = left; M2 = - K- M1; int c1, C2; // find the first number c1, if the total is an odd number, returns C1 = max (M1 <= 0 INT_MIN: nums1 [Ml-? . 1 ] , M2 <= 0 ? INT_MIN: nums2 [M2- . 1 ]); IF ((N1 + N2) & . 1 == . 1 ) return C1; // find the second number c2, and returns (c1 + c2) / 2 min = C2 (M1> N1 = INT_MAX: nums1 [M1], M2> = N2?? INT_MAX: nums2 [M2]); return Double (C1 + C2) * 0.5 ; } };
Method two: Merge ordered array
O(log(m+n+1)/2)
class Solution { public : Double findMedianSortedArrays (Vector < int > & nums1, Vector < int > & nums2) { // O (n-m + +. 1) / 2 Space O (n-) solution of time, size of the obtained two num1 (), respectively, with two pointers to two arrays, each of the small rearward displacement int N1 = nums1.size (); int N2 = nums2.size (); int ID1, ID2; int MID = ( + N2 + N1 . 1 ) / 2 ; int I = 0 , J = 0 ; int CUR = INT_MIN; the while ! (MID = 0 && I <N1 && J <n2){ mid--; if(nums1[i]<nums2[j]) id1=nums1[i++]; else id1=nums2[j++]; } while(mid!=0&&i<n1){ mid--; id1=nums1[i++]; } while(mid!=0&&j<n2){ mid--; id1=nums2[j++]; } if((n1+n2)%2==1) return id1; id2=min((j>=n2?INT_MAX:nums2[j]),(i>=n1?INT_MAX:nums1[i])); return double(id1+id2)*0.5; } };