题目描述
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)).
题目要求寻找两个已排序数组的中位数
解题代码
本题我使用了比较傻瓜的方法去解决这个问题。如果两个数组均不为空,则将两个数组合并为一个数组,然后再获得合并后的数组的中位数。
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if (nums1.empty() && nums2.empty())
{
return 0;
}
else if (!nums1.empty() && nums2.empty())
{
int size = nums1.size();
if (size % 2 == 0)
return (nums1[size / 2] + nums1[size / 2 - 1]) / 2.0;
else
return nums1[size / 2];
}
else if (nums1.empty() && !nums2.empty())
{
int size = nums2.size();
if (size % 2 == 0)
return (nums2[size / 2] + nums2[size / 2 - 1]) / 2.0;
else
return nums2[size / 2];
}
bool isEven = (nums1.size() + nums2.size()) % 2 == 0;
int count = (nums1.size() + nums2.size()) / 2 + 1;
vector<int> union_nums;
vector<int>::iterator it1 = nums1.begin();
vector<int>::iterator it2 = nums2.begin();
vector<int>::iterator it1_end = nums1.end();
vector<int>::iterator it2_end = nums2.end();
for(size_t i = 0; i != count; ++i)
{
if(it1 != it1_end && it2 != it2_end)
{
if(*it1 < * it2)
{
union_nums.push_back(*it1);
it1++;
}
else
{
union_nums.push_back(*it2);
it2++;
}
}
else if (it1 == it1_end)
{
union_nums.push_back(*it2);
it2++;
}
else
{
union_nums.push_back(*it1);
it1++;
}
}
if(isEven) return (union_nums[count-1]+union_nums[count-2])/2.0;
else return union_nums[count-1];
}
};