思路:
那么如果左半边全小于右半边,如果左边的元素个数相加刚好等于k, 那么第k个元素就是Max(LMax1, LMax2),这个比较好理解的,因为Max(LMax1, LMax2)肯定是左边k个元素的最大值,因为合并后的数组是有序,第k个元素肯定前面k个元素中最大的那个。
public double findMedianSortedArrays(int[] nums1, int[] nums2){
if(nums1.length>nums2.length){
int[] temp=nums1;
nums1=nums2;
nums2=temp;
}
int m=nums1.length;
int n= nums2.length;
int total=(m+n+1)/2;//无论奇偶都可以统一这样写
int left=0;
int right=m;
while(left<right){
int i=left+(right-left+1)/2;//i指向分割的右侧
int j=total-i;
if(nums1[i-1]>nums2[j]){
right=i-1;
}
else{
left=i;
}
}
int c1=left;//nums1分割的位置
int c2=total-c1;
int nums1LeftMax=(c1==0)?Integer.MIN_VALUE:nums1[c1-1];
int nums2LeftMax=(c2==0)?Integer.MIN_VALUE:nums2[c2-1];
int nums1RightMax=(c1==m)?Integer.MAX_VALUE:nums1[c1];
int nums2RightMax=(c2==n)?Integer.MAX_VALUE:nums2[c2];
if((m+n)%2==0){
return (Math.max(nums1LeftMax,nums2LeftMax)+Math.min(nums1RightMax,nums2RightMax))/2.0;
}
else{
return Math.max(nums1LeftMax,nums2LeftMax);
}
}