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)).
Subscribe to see which companies asked this question
class Solution
{
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
int m = nums1.size();
int n = nums2.size();
//cout << m << " " << n << endl;
if ((m+n)%2 == 0)
{
//cout << "even" << endl;
return (findKthNum(nums1, nums2, (m + n) / 2) + findKthNum(nums1, nums2, (m + n) / 2 + 1))/2;
}
else
{
//cout << "odd" << endl;
return findKthNum(nums1, nums2, (m + n) / 2 + 1);
}
}
int min(int a, int b)
{
if (a < b)
{
return a;
}
else
{
return b;
}
}
double findKthNum(vector<int>& nums1, vector<int>& nums2, int k)
{
if (nums1.size() > nums2.size())
{
return findKthNum(nums2, nums1, k); //注意nums1的size一定要比nums2小,不然会发生溢出错误
}
//当m或者n为0时
if (nums1.size() == 0)
{
if (k <= nums2.size())
return nums2[k - 1];
}
else if (nums2.size() == 0)
{
return nums1[k - 1];
}
//当k为1时
if (k == 1)
{
return min(nums1[0], nums2[0]);
}
int offset_1 = min(k / 2, nums1.size());
int offset_2 = k - offset_1;
vector<int> new_nums1, new_nums2;
int i = 0;
if (nums1[offset_1-1] == nums2[offset_2-1])
{
return nums1[offset_1-1];
}
else if (nums1[offset_1-1] < nums2[offset_2-1])
{
for (vector<int>::iterator it = nums1.begin(); it != nums1.end(); it++)
{
if (i >= offset_1)
{
new_nums1.push_back(*it);
}
i++;
}
return findKthNum(new_nums1, nums2, k - offset_1);
}
else
{
for (vector<int>::iterator it = nums2.begin(); it != nums2.end(); it++)
{
if (i >= offset_2)
{
new_nums2.push_back(*it);
}
i++;
}
return findKthNum(nums1, new_nums2, k - offset_2);
}
}
};