Question:
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Solution:
1 double findk(vector<int> nums1,vector<int> nums2,int k) 2 { 3 int M=nums1.size(); 4 int N=nums2.size(); 5 if(M>N) return findk(nums2,nums1,k); 6 else 7 { 8 if(nums1.empty()) return nums2[k-1]; 9 if(k==1) return min(nums1[k-1],nums2[k-1]); 10 int ia=min(k/2,M); 11 int ib=k-ia; 12 if(nums1[ia-1]<nums2[ib-1]) 13 { 14 vector<int> tmp1(nums1.begin()+ia,nums1.end()); 15 vector<int> tmp2(nums2.begin(),nums2.end()); 16 return findk(tmp1,tmp2,k-ia); 17 } 18 else if(nums1[ia-1]>nums2[ib-1]) 19 { 20 vector<int> tmp1(nums1.begin(),nums1.end()); 21 vector<int> tmp2(nums2.begin()+ib,nums2.end()); 22 return findk(tmp1,tmp2,k-ib); 23 } 24 else 25 { 26 return nums1[ia-1]; 27 } 28 } 29 } 30 class Solution { 31 public: 32 double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) 33 { 34 int M=nums1.size(); 35 int N=nums2.size(); 36 int total=M+N; 37 if(total%2!=0) 38 return findk(nums1,nums2,total/2+1); 39 else 40 return (findk(nums1,nums2,total/2)+findk(nums1,nums2,total/2+1))/2.0; 41 } 42 };