参考博客:https://blog.csdn.net/chen_xinjia/article/details/69258706
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int MIN_VALUE = 0x80000000;
int MAX_VALUE = 0x7FFFFFFF;
int N1 = nums1.length;
int N2 = nums2.length;
int size = N1 + N2;
if(N1 > N2){//保证nums1最短
return findMedianSortedArrays(nums2, nums1);
}
if(N1 == 0){
return ((double)nums2[(N2 - 1) / 2 ] + (double)nums2[N2 / 2]) / 2;
}
int CutL = 0,CutR = N1;
int cut1 = N1 / 2;
int cut2 = size / 2 - cut1;
while(cut1 <= N1){
cut1 = (CutR - CutL) / 2 + CutL;
cut2 = size / 2 - cut1;
int L1 = cut1 == 0 ? MIN_VALUE : nums1[cut1 - 1];
int R1 = cut1 == N1 ? MAX_VALUE : nums1[cut1];
int L2 = cut2 == 0 ? MIN_VALUE : nums2[cut2 - 1];
int R2 = cut2 == N2 ? MAX_VALUE : nums2[cut2];
if(L1 > R2){
CutR = cut1 - 1;
}else if(L2 > R1){
CutL = cut1 + 1;
}else{
if(size % 2 == 0){
L1 = L1 > L2 ? L1 : L2 ;
R1 = R1 < R2 ? R1 : R2;
return (double)(L1 + R1) / 2;
}else{
return R1 < R2 ? R1 : R2;
}
}
}
return -1;
}
}