题目描述
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(log(m+n));
开始时我使用线性扫描的方式找到中间值,但是就不满足时间复杂度要求了。
然后参考了别人的一个解答@参考代码,使用二分查找。
比较难理解。
代码
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
int m=nums1.size(),n=nums2.size();
int K=(m+n)/2;
if(m+n == 0)
{
return -1;
}
else if((m+n)%2==1)//odd
{
return findKth(nums1,0,m,nums2,0,n,K);
}
else //even
{
return (findKth(nums1,0,m,nums2,0,n,K) + findKth(nums1,0,m,nums2,0,n,K-1))/2;
}
}
double findKth(vector<int>&nums1,int L1,int len1,vector<int>&nums2,int L2,int len2,int K)
{
if(len1>len2)
{
return findKth(nums2,L2,len2,nums1,L1,len1,K);
}
if(len1 == 0)//如果第一个数组为空
{
return (double) nums2[L2+K];
}
if(K==len1+len2-1)//最终会变为找两个数组中的最大值?????为什么
{
return (double)max(nums1[L1+len1-1],nums2[L2+len2-1]);
}
int i = len1/2;//二分查找
int j = K-i;
if(nums1[L1+i]>nums2[L2+j])
{
return findKth(nums1,L1,i,nums2,L2+j,len2-j,i);//去掉L2前面的j个数,去掉L1以及L1之后的数,处理后找下标为K-j=i的数
}
else
{
return findKth(nums1,L1+i,len1-i,nums2,L2,j,j);//去掉L1前面的i个数,去掉L2以及L2之后的数,处理后找下标为K-i=j的数
}
}
};