不积跬步无以至千里
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)).
You may assume nums1 and nums2 cannot be both empty.
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) )的的时间复杂度就有点意思了。找到了数组A和数组B之间中位数的关系,把两个数组都分成两段,A分为两段,B分为两段,然后什么时候A和B的前两段的最大值小于A和B的后两段的最小值
就说明找到中位数的位置了。两个数组的分段位置符合 i + j = m + n +1 (奇数偶数的总长度都可以用这个关系,因为int类型不会四舍五入),有了这样的关系,就可以根据两个分段的最大最小值来调整分段的位置。
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int>As = nums1.size()<nums2.size()?nums1:nums2;
vector<int>Bs = nums1.size()>=nums2.size()?nums1:nums2;
int m=As.size(),n=Bs.size();
if(m==0)
return (Bs[(n-1)/2]+Bs[(n-1)/2+(n-1)%2])/2.0;
int i,j,start=0,end=m,left,right;
while(start<=end)
{
i = (start + end)/2;
j = (m+n+1)/2-i;
if(i<end&&Bs[j-1]>As[i])
start = i+1;
else if(i>start&&As[i-1]>Bs[j])
end = i-1;
else
{
if(i == 0)
left = Bs[j-1];
else if(j==0)
left = As[i-1];
else
left = max(As[i-1],Bs[j-1]);
if((m+n)%2==1)
return left;
if(i==m)
right = Bs[j];
else if(j==n)
right = As[i];
else
right = min(As[i],Bs[j]);
return (left+right)/2.0;
}
}
return 0;
}
};