解释:
从这两组排好序的数列中,找出这两个数列中包含的所有数的中位数,要求时间复杂度为O(m+n),m,n分别为两个数组的长度。
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
if(len1 == 0||len2 == 0)
{
if(len1 == 0&& len2 == 0)
return 0;
else if(len1==0)
return findTheMedian(nums2);
else if(len2 == 0)
return findTheMedian(nums1);
}
int len = len1+len2;
if(len%2 == 0)
return findTheKestMinValue(nums1,0,nums2,0,len/2)/2.0 + findTheKestMinValue(nums1,0,nums2,0,len/2+1)/2.0;
else
return findTheKestMinValue(nums1,0,nums2,0,len/2+1);
}
double findTheMedian(vector<int> nums)
{
int len = nums.size();
if(len == 1)
return nums.at(0);
if(len == 2)
return (nums.at(0)+nums.at(1))/2.0;
if(len %2 == 0)
return nums.at(len/2)/2.0+nums.at(len/2-1)/2.0;
else
return nums.at(len/2);
}
int findTheKestMinValue(vector<int> nums1,int i1,vector<int> nums2,int i2,int k)
{
if(i1 >= nums1.size())
return nums2[i2+k-1];
if(i2 >= nums2.size())
return nums1[i1+k-1];
if(k == 1)
return std::min(nums1.at(i1),nums2.at(i2));
int key1 ;
int key2 ;
if(i1+k/2-1 >= nums1.size())
key1 = INT_MAX;
else
key1 = nums1.at(i1+k/2-1);
if(i2+k/2-1 >= nums2.size())
key2 = INT_MAX;
else
key2 = nums2.at(i2+k/2-1);
if(key1 > key2)
return findTheKestMinValue(nums1,i1,nums2,i2+k/2,k -(k/2));
if(key1 <= key2)
return findTheKestMinValue(nums1,i1+k/2,nums2,i2,k -(k/2));
}
};