寻找两个正序数组的中位数
问题:寻找两个正序数组的中位数
解答:
题解,方法二
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int n = nums1.size(); int m = nums2.size(); //保证数组1一定最短 //为了加快速度 对长度短的进行二分 if (n>m) { return findMedianSortedArrays(nums2,nums1); } int lmax1 = 0, lmax2 = 0, rmin1 = 0, rmin2 = 0; int c1,c2; int low = 0,high = n; while(low<=high) { c1 = (high+low+1)/2; c2 = (m+n)/2-c1; lmax1 = c1==0 ? INT_MIN : nums1[c1-1]; rmin1 = c1==n ? INT_MAX : nums1[c1]; lmax2 = c2==0 ? INT_MIN : nums2[c2-1]; rmin2 = c2==m ? INT_MAX : nums2[c2]; if(lmax1>rmin2) { high = c1-1; } else if (lmax2>rmin1) { low = c1+1; } else break; } cout<<lmax1<<" "<<lmax2<<" "<<rmin1<<" "<<rmin2<<endl; if((m+n)%2) return min(rmin1,rmin2); else return (max(lmax1,lmax2)+min(rmin1,rmin2))/2.0; } };