题解报告LeetCode#4:寻找两个有序数组的中位数
题意:LeetCode#4:寻找两个有序数组的中位数;他山之玉:liweiwei1419
思路:“使用二分查找找到两个数组的边界线”
中位数:在有两个有序数组的时候,仍然可以把两个数组分割成两个部分。
我们使用一条分割线把两个数组分别分割成两部分:
- 红线左边和右边的元素个数相等,或者左边元素的个数比右边元素的个数多 1 个;
- 红线左边的所有元素的数值 <= 红线右边的所有元素的数值;
那么中位数就一定只与红线两侧的元素有关,确定这条红线的位置使用二分查找。
代码:
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
// 为了让搜索的范围更小,我们始终让 nums1 是那个更短的数组
if (nums1.length > nums2.length) {
int[] temp = nums1;
nums1 = nums2;
nums2 = temp;
}
int m = nums1.length;
int n = nums2.length;
// 分割线左边的所有元素需要满足的个数 m + (n - m + 1) / 2;
int totalLeft = (m + n + 1) / 2;
// 在 nums1 的区间 [0, m] 里查找恰当的分割线
// 使得 nums1[i - 1] <= nums2[j] && nums2[j - 1] <= nums1[i]
int left = 0;
int right = m;
while (left < right) {
int i = left + (right - left + 1) / 2;
int j = totalLeft - i;
if (nums1[i - 1] > nums2[j]) {
// 下一轮的搜索区间 [left, i - 1]
right = i - 1;
} else {
// 下一轮的搜索区间 [i, right]
left = i;
}
}
int i = left;
int j = totalLeft - i;
int nums1LeftMax = i == 0 ? Integer.MIN_VALUE : nums1[i - 1];
int nums1RightMin = i == m ? Integer.MAX_VALUE : nums1[i];
int nums2LeftMax = j == 0 ? Integer.MIN_VALUE : nums2[j - 1];
int nums2RightMin = j == n ? Integer.MAX_VALUE : nums2[j];
if (((m + n) % 2) == 1) {
return Math.max(nums1LeftMax, nums2LeftMax);
} else {
return (double) ((Math.max(nums1LeftMax, nums2LeftMax)) +
(Math.min(nums1RightMin, nums2RightMin))) / 2;
}
}
}