Problem:
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)).
Analysis:
Solution:
double FindMedianAux(vector<int>& nums1, int start1, int end1,
vector<int>& nums2, int start2, int end2,
int position)
{
if (end1 < start1)
return double(nums2[start2 + position]);
if (end2 < start2)
return double(nums1[start1 + position]);
int mid1 = start1 + (end1 - start1) / 2;
int mid2 = start2 + (end2 - start2) / 2;
if (nums1[mid1] > nums2[mid2])
return FindMedianAux(nums2, start2, end2,
nums1, start1, end1, position);
int lower_part = mid1 - start1 + mid2 - start2 + 1;
if (nums1[end1] <= nums2[start2]) {
if (position <= end1 - start1)
return nums1[start1 + position];
else
return nums2[start2 + position - (end1 - start1 + 1)];
}
else if (position <= 0) {
return double(nums1[start1] < nums2[start2] ?
nums1[start1] : nums2[start2]);
}
else {
if (position >= lower_part)
return FindMedianAux(nums1, mid1 + 1, end1,
nums2, start2, end2, position - (mid1 - start1 + 1));
else
return FindMedianAux(nums1, start1, end1,
nums2, start2, mid2 - 1, position);
}
}
double FindMedianNumber(vector<int>& nums1, vector<int>& nums2)
{
int m = nums1.size();
int n = nums2.size();
if ((m + n) % 2 == 0)
return (FindMedianAux(nums1, 0, m - 1,
nums2, 0, n - 1, (m + n) / 2 - 1)
+ FindMedianAux(nums1, 0, m - 1,
nums2, 0, n - 1, (m + n) / 2)) / 2;
else
return FindMedianAux(nums1, 0, m - 1,
nums2, 0, n - 1, (m + n) / 2);;
}