有两个大小分别为 m 和 n 的排序数组 nums1 和 nums2。求两个排序数组的中位数。总体运行时间复杂度应为 O(log (m+n))。
示例 1:nums1 = [1, 3] nums2 = [2]
中位数为 2.0
示例 2:nums1 = [1, 2] nums2 = [3, 4]
中位数为 (2 + 3)/2 = 2.5
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
// Deal with invalid corner case.
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) return 0.0;
int m = nums1.length, n = nums2.length;
int l = (m + n + 1) / 2; //left half of the combined median
int r = (m + n + 2) / 2; //right half of the combined median
// If the nums1.length + nums2.length is odd, the 2 function will return the same number
// Else if nums1.length + nums2.length is even, the 2 function will return the left number and right number that make up a median
return (getKth(nums1, 0, nums2, 0, l) + getKth(nums1, 0, nums2, 0, r)) / 2.0;
}
private double getKth(int[] nums1, int start1, int[] nums2, int start2, int k) {
// This function finds the Kth element in nums1 + nums2
// If nums1 is exhausted, return kth number in nums2
if (start1 > nums1.length - 1) return nums2[start2 + k - 1];
// If nums2 is exhausted, return kth number in nums1
if (start2 > nums2.length - 1) return nums1[start1 + k - 1];
// If k == 1, return the first number
// Since nums1 and nums2 is sorted, the smaller one among the start point of nums1 and nums2 is the first one
if (k == 1) return Math.min(nums1[start1], nums2[start2]);
int mid1 = Integer.MAX_VALUE;
int mid2 = Integer.MAX_VALUE;
if (start1 + k / 2 - 1 < nums1.length) mid1 = nums1[start1 + k / 2 - 1];
if (start2 + k / 2 - 1 < nums2.length) mid2 = nums2[start2 + k / 2 - 1];
// Throw away half of the array from nums1 or nums2. And cut k in half
if (mid1 < mid2) {
return getKth(nums1, start1 + k / 2, nums2, start2, k - k / 2); //nums1.right + nums2
} else {
return getKth(nums1, start1, nums2, start2 + k / 2, k - k / 2); //nums1 + nums2.right
}
}
我明白为什么要去掉一个数组的 k/2。如果 aMid 小于 bMid,那么混合数组中 aMid 的最大索引是 k-1,因为 B 中最多 k/2-1 个 nums混合时将插入到aMid之前的位置,因为B中的第k/2个元素大于aMid。
请解释为什么 kk/2 在下一次迭代中,因为在第一次迭代中,您删除了 k/2 个不可能成为合并数组中的第 k 个条目的条目。
例如
A 中的 0 到 k/2-1 个条目被删除,因为 aMid 小于 bMid ,这意味着 aMid 最多是第 (k-1) 个条目。但是,在 B 数组中仍有 k/2 个条目不能排除。在下一次迭代函数中getkth(A, aStart + k/2, B, bStart, k - k/2) bMid=B[0+k/4-1],aMid=A[3k/4-1]。怎么样左边的 B[k/4 到 k/2] 个条目?
没有理由排除它们。这个算法的迭代机制是什么?