给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
算法的时间复杂度应该为 O(log (m+n)) 。
示例 1:
输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2
示例 2:
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
提示:
nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/median-of-two-sorted-arrays
#include<iostream>
#include<vector>
using namespace std;
/*思路:最容易想到的就是新开一个数组把两个数组合并重新排序,然后取中位数。时空复杂度都为O(m+n)。改进之后用双指针从两个数组依次读数找中位数,可以不用开存储空间。O(log(m+n))复杂度应该会涉及2分查找。*/
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int _len1 = (int)nums1.size(), _len2 = (int)nums2.size();
int _len = _len1 + _len2;
int a1 = 0, a2 = 0;
if (_len1 == 0)
{
if (_len2 % 2 == 1)
return (double)nums2[_len2 / 2];
else
return (double)((nums2[_len2 / 2] + nums2[_len2 / 2 - 1]) / 2.0);
}
if (_len2 == 0)
{
if (_len1 % 2 == 1)
return (double)nums1[_len1 / 2];
else
return (double)((nums1[_len1 / 2] + nums1[_len1 / 2 - 1]) / 2.0);
}
if (_len % 2 == 0)
{
a1 = findXth(nums1, nums2, _len / 2, 0, 0);
a2 = findXth(nums1, nums2, (_len / 2)-1, 0, 0);
return (a1 + a2) / 2.0;
}
else
{
a1 = findXth(nums1, nums2, _len / 2, 0, 0);
return a1;
}
}
int findXth(const vector<int>& nums1, const vector<int>& nums2, int k, int left1, int left2)
{
int _index1 = 0, _index2 = 0;
int _left1 = left1, _right1 = nums1.size() - 1;
int _left2 = left2, _right2 = nums2.size() - 1;
if (nums1.size() > nums2.size())
return findXth(nums2, nums1, k, _left1, _left2);//让nums1数组总是最小
//nums1中元素都被pass掉了
if (_left1 > _right1)
{
return nums2[_left2 + k];
}
if (_left2 > _right2)
return nums1[_left1 + k];
if (k == 0)
return nums1[_left1] <= nums2[_left2] ? nums1[_left1] : nums2[_left2];
if (k == 1)
{
_index1 = _left1;
_index2 = _left2;
if (nums1[_index1] <= nums2[_index2])
_left1++;
else
_left2++;
k -= 1;
return findXth(nums1, nums2, k, _left1, _left2);
}
if (_right1 - _left1 + 1 <= k / 2)
{
_index1 = _right1;
_index2 = _left2;
if (nums1[_index1] <= nums2[_index2])
return nums2[_left2 + k - (_right1 - _left1 + 1)];
else
{
_left2 += (k / 2);
k -= (k / 2);
return findXth(nums1, nums2, k, _left1, _left2);
}
}
_index1 = _left1 + k / 2 - 1;
_index2 = _left2 + k / 2 - 1;
if (nums1[_index1] <= nums2[_index2])
_left1 += (k / 2);
else
_left2 += (k / 2);
k -= (k / 2);
return findXth(nums1, nums2, k, _left1, _left2);
}
};
//test
int main()
{
vector<int>n1, n2;
int m1, m2, m3;
cin >> m1;
for (int i = 0; i < m1; i++)
{
cin>>m2;
n1.push_back(m2);
}
cin >> m3;
for (int i = 0; i < m3; i++)
{
cin >> m2;
n2.push_back(m2);
}
Solution s1;
printf("%lf", s1.findMedianSortedArrays(n1, n2));
}