题目链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
题目描述:
题解:
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
double ans = 0;
int len = nums1.size() + nums2.size();
if(len % 2 == 0)
ans = (getNum(nums1, nums2, len / 2 - 1) + getNum(nums1, nums2, len / 2)) / 2;
else
ans = getNum(nums1, nums2, len / 2);
return ans;
}
//归并排序
double getNum(vector<int>& nums1, vector<int>& nums2, int k)
{
vector<int> result(nums1.size() + nums2.size(), -1);
int i = 0, j = 0;
int cur = 0;
while( i < nums1.size() && j < nums2.size() && cur <= k)
{
if(nums1[i] < nums2[j])
result[cur++] = nums1[i++];
else
result[cur++] = nums2[j++];
}
while(i < nums1.size() && cur <= k)
result[cur++] = nums1[i++];
while(j < nums2.size() && cur <= k)
result[cur++] = nums2[j++];
return result[cur - 1];
}
};