给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。
请你找出这两个正序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0
示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5
头文件
#include <vector>
#include <iostream>
using namespace std;
解决方案类:
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len;
double Median_Num;
nums1.insert(nums1.end(), nums2.begin(), nums2.end());
len = nums1.size();
QKSort(nums1, 0, len-1);
for (int i = 0; i < len; i++)
{
cout << nums1[i];
cout << " ";
}
cout << endl;
if (len % 2 == 1)
{
Median_Num = nums1[len / 2];
return(Median_Num);
}
else
{
Median_Num = ((double)nums1[len / 2 - 1] + (double)nums1[len / 2]) / 2;
return(Median_Num);
}
}
void QKSort(vector<int>& r, int low, int high) { //冒泡排序
if (low < high) {
int pos = QKPass(r, low, high);
QKSort(r, low, pos-1);
QKSort(r, pos + 1, high);
}
}
int QKPass(vector<int>& r, int left, int right) {
int x = r[left];
int low = left;
int high = right;
while (low < high)
{
while (low < high && r[high] >= x)
{
high--;
}
if (low < high)
{
r[low] = r[high];
low++;
}
while (low < high && r[low] < x)
{
low++;
}
if (low < high)
{
r[high] = r[low];
high--;
}
}
r[low] = x;
return low;
}
};
主函数
int main() {
Solution s;
vector<int> a = {1, 3};
vector<int> b = {2, 4};
double result = s.findMedianSortedArrays(a, b);
cout << result << endl;
return 0;
}
结果