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)).
You may assume nums1 and nums2 cannot be both empty.
solution:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int> tmp;
vector<int> tmp_long;
vector<int> tmp_short;
if (nums1.size() == 0)
tmp = nums2;
if (nums2.size() == 0)
tmp = nums1;
if (tmp.size() % 2 == 0 && tmp.size() != 0)
return (double)(tmp[tmp.size() / 2] + tmp[tmp.size() / 2 - 1]) / 2;
if (tmp.size() % 2 != 0)
return tmp[tmp.size() / 2];
if (nums1.size() < nums2.size())
{
tmp_long = nums2;
tmp_short = nums1;
}
else
{
tmp_long = nums1;
tmp_short = nums2;
}
int count = 0;
int temp = nums1[0] < nums2[0] ? nums1[0] : nums2[0];
int j_index = 0;
int median_number = (nums1.size() + nums2.size()) / 2 + 1;
for (int i = 0; i < tmp_long.size();)
{
if (tmp_long[i] <= temp)
{
tmp.push_back(tmp_long[i]);
count++;
i++;
if (count == median_number)
break;
if (i < tmp_long.size())
continue;
}
else
temp = tmp_long[i];
for (int j = j_index; j < tmp_short.size();)
{
if (tmp_short[j] <= temp)
{
tmp.push_back(tmp_short[j]);
count++;
j_index++;
j++;
if (count == median_number)
break;
}
else
{
temp = tmp_short[j];
if(i !=tmp_long.size())
break;
}
}
if (count == median_number)
break;
}
if ((nums1.size() + nums2.size()) % 2 == 0)
return (double)(tmp[tmp.size() - 1] + tmp[tmp.size() - 2]) / 2;
else
return tmp[tmp.size() - 1];
}