【LeetCode & 剑指offer刷题】查找与排序题4:Median of Two Sorted Arrays
【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)
Median of Two Sorted Arrays
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(m+n),不满足题意
class Solution
{
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
int i=0,j=0,k=0;
int m = nums1.size();
int n = nums2.size();
int len = m+n;
vector<int> temp(len);
while(i<m&&j<n) //合并,耗时O(m+n)
{
temp[k++] = (nums1[i]<nums2[j])? nums1[i++]:nums2[j++];
}
while(i<m)
{
temp[k++] = nums1[i++];
}
while(j<n)
{
temp[k++] = nums2[j++];
}
double mid; //注意这里类型为浮点数,因为可能为小数
if(len&1)
mid = temp[(len-1)/2];//长度为奇数时,中值为中间数
else
mid = (temp[(len-1)/2]+temp[len/2])/2.0;//长度为偶数时,中值为中间两数平均数
return mid;
}
};
//方法二:递归,利用二分查找
//没看懂??
class Solution
{
public:
int getkth(vector<int>& s, int m, vector<int>& l, int n, int k)
{
//让m<=n
if(m>n) return getkth(l,n,s,m,k);
if(m==0) return l[k-1];
if(k == 1) return min(s[0], l[0]);
int i = min(m, k/2),j = min(n,k/2);
if(s[i-1] > l[j-1]) return getkth(s,m,, n-j, k-j);
else return getkth(s+i, m-i, l, n, k-i);
return 0;
}
double findMedianSortedArrays(vector<int>& a, vector<int>& b)
{
int m = a.size();
int n = b.size();
int l = (m+n+1) >> 1;
int r = (m+n+2) >> 1;
return (getkth(a,m,b,n,l) + getkth(a,m,b,n,r))/2.0;
}
};