题目描述:
解法:
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if(nums1.size()>nums2.size()) return findMedianSortedArrays(nums2,nums1); //这一步必须要记得写,否则cut2会出现错误索引
int m=nums1.size();
int n=nums2.size();
int Lmax1,Rmin1,Lmax2,Rmin2,cut1,cut2;
int left=0,right=2*m; //增加虚拟位 #1#3#
while(left<=right){ //二分nums1
cut1=(left+right)/2;
cut2=m+n-cut1;
Lmax1=cut1<=0? INT_MIN:nums1[(cut1-1)/2]; //虚拟位寻址
Rmin1=cut1>=2*m? INT_MAX:nums1[cut1/2];
Lmax2=cut2<=0? INT_MIN:nums2[(cut2-1)/2];
Rmin2=cut2>=2*n? INT_MAX:nums2[cut2/2];
if(Lmax1>Rmin2){
right=cut1-1;
}
else if(Lmax2>Rmin1){
left=cut1+1;
}
else break;
}
return (max(Lmax1,Lmax2)+min(Rmin1,Rmin2))/2.0;
}
};