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)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
时间复杂度为O(nlogn)的解法
class Solution {
public:
/*时间复杂度为O(nlogn),空间复杂度为O(n)*/
double findMedianSortedArrays_1(vector& nums1, vector& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
if (len1 == 0 && len2 == 0)
return 0;
if (len1 == 0 && len2 == 1)
return nums2[0];
if (len1 == 1 && len2 == 0)
return nums1[0];
vector nums;
for (int i = 0; i < len1;i++)
nums.push_back(nums1[i]);
for (int i = 0; i < len2;i++)
nums.push_back(nums2[i]);
sort(nums.begin(), nums.end());
int len = nums.size();
if ((len & 1) == 1)
return nums[len / 2];
else
{
return (nums[len / 2 - 1] + nums[len / 2]) / 2.0;
}
}
};
class Solution {
public:
/*时间复杂度为O(n)的解法*/
//设置两个指针同时遍历两个数组,计数,找到中位数
double findMedianSortedArrays_2(vector& nums1, vector& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
if (len1 == 0 && len2 == 0)
return 0;
int median = (len1 + len2) / 2;
bool flag = (len1 + len2) & 1;
int i = 0, j = 0;
while (i < len1&&j < len2)
{
if (nums1[i] < nums2[j])
{
median--;
if (median == 0)
{
if (flag)
return nums1[i];
else
{
if (nums1[i + 1] < nums2[j])
return (nums1[i] + nums1[i + 1]) / 2.0;
else
return (nums1[i] + nums2[j]) / 2.0;
}
}
i++;
}
else
{
median--;
if (median == 0)
{
if (flag)
return nums1[j];
else
{
if (nums1[j + 1] < nums2[i])
return (nums1[j] + nums1[j + 1]) / 2.0;
else
return (nums1[i] + nums2[j]) / 2.0;
}
}
j++;
}
}
if (i + j < median)
{
if (i == len1)
return nums2[median - (i + j)];
else
return nums1[median - (i + j)];
}
}
};
时间复杂度为O(log(m+n))的解法:
class Solution {
public:
double findMedianSortedArrays(vector& nums1, vector& nums2) {
int m = nums1.size();
int n = nums2.size();
if (((m + n) & 1) == 1)
return findKth((m + n - 1) / 2, nums1, 0, m - 1, nums2, 0, n - 1);
else
{
int x = findKth((m + n) / 2 - 1, nums1, 0, m - 1, nums2, 0, n - 1);
int y = findKth((m + n) / 2, nums1, 0, m - 1, nums2, 0, n - 1);
return (x + y) / 2.0;
}
}
int findKth(int k, vector a, int l1, int r1, vector b, int l2, int r2)
{
if (l1 > r1)
return b[l2 + k];
if (l2 > r2)
return a[l1 + k];
int m1 = (l1 + r1) / 2;
int m2 = (l2 + r2) / 2;
if (a[m1] > b[m2])
{
if (k + 1 < m1 - l1 + 1 + m2 - l2 + 1)
return findKth(k, a, l1, m1 - 1, b, l2, r2);
else
return findKth(k-(m2-l2+1), a, l1, r1, b, m2 + 1, r2);
}
else
{
if (k + 1 < m1 - l1 + 1 + m2 - l2 + 1)
return findKth(k, a, l1, r1, b, l2, m2 - 1);
else
return findKth(k - (m1 - l1 + 1), a, m1 + 1, r1, b, l2, r2);
}
}
};