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)).
You may assume nums1 and nums2 cannot be both empty.
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
c ++ ideas: because the topics required to achieve the algorithm complexity O (m + n), so we can only facilitate the conduct of the primary array. My approach is to be stored in order to save the sequence with a vector. After determining the size it is even? It returns the index of the even-numbered and two intermediate numbers. What is odd? Returns a middle odd number. In addition to the pursuit of short and pithy than good code, still requires a certain readability.
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { vector<int> merge; int i=0,j=0; while(true){ if(i<nums1.size()&&j<nums2.size())//i,j都有效 if(nums1[i]<nums2[j]) merge.push_back(nums1[i++]); else merge.push_back(nums2[j++]); if(i>=nums1.size()) while(j<nums2.size()) merge.push_back(nums2[j++]); if(j>=nums2.size()) while(i<nums1.size()) merge.push_back(nums1[i++]); if(i>=nums1.size()&&j>=nums2.size()) break; } if(merge.size()%2==0) return (merge[merge.size()/2]*1.0+merge[merge.size()/2-1]*1.0)/2.0; else return merge[merge.size()/2]*1.0; } };