思路:需要给出两个有序数组一个恰当的分割线,中位数的值就由位于这个分割线的两侧的数决定。确定分割线的位置可以用二分查找法。
时间复杂度 O(log min(m,n))
空间复杂度 O(1)
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
double ret = 0;
if (nums1.length > nums2.length) {
return findMedianSortedArrays(nums2, nums1);
}
int m = nums1.length;
int n = nums2.length;
int totalLeft = (m + n + 1) / 2; // 这里 +1 也很灵性,可能整形越界哦!对这道题无所谓
int left = 0;
int right = m;
while(left < right) {
int i = left + (right - left + 1) / 2; // +1 真的灵性
int j = totalLeft - i;
// 由于 i 一定大于 left,所以最后left 和 right 一定相等,又躲过一个坑
if (nums1[i - 1] > nums2[j]) { // 不用判断越界,太棒了
right = i - 1;
} else {
left = i;
}
}
int nums1SplitLeft = left == 0 ? Integer.MIN_VALUE : nums1[left - 1];
int nums1SplitRight = left == m ? Integer.MAX_VALUE : nums1[left];
int j = totalLeft - left;
int nums2SplitLeft = j == 0 ? Integer.MIN_VALUE : nums2[j-1];
int nums2SplitRight = j == n ? Integer.MAX_VALUE : nums2[j];
if ((m + n) % 2 == 1) {
ret = Math.max(nums1SplitLeft, nums2SplitLeft);
} else {
ret = (Math.max(nums1SplitLeft, nums2SplitLeft) + Math.min(nums1SplitRight, nums2SplitRight)) / 2.0;
}
return ret;
}
}