There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3] nums2 = [2] The median is 2.0
Example 2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
这是一道非常经典的题。这题更通用的形式是,给定两个已经排序好的数组,找到 两者所有元素中第k 大的元素。
O(m+n) 的解法比较直观,直接merge两个数组,然后求第k 大的元素。
不过我们仅仅需要第k 大的元素,是不需要“排序”这么昂贵的操作的。可以用一个计数器,记录当前已经找到第m 大的元素了。同时我们使用两个指
针pA 和pB ,分别指向A和B数组的第一个元素,使用类似于merge sort的原理, 如果数组A当前元素小,那么pA++ ,同时m++ ;如果数组B当前元素小,那
么pB++ ,同时m++ 。最终当m 等于k 的时候,就得到了我们的答
案,O(k) 时间,O(1) 空间。但是,当k 很接近m+n 的时候,这个方法还是 O(m+n) 的 。
有没有更好的方案呢?我们可以考虑从k 入手。如果我们每次都能够删除一个一定在第k 大元素之前的元素,那么我们需要进行k 次。但是如果每次我们都删除一半呢?由于A和B都是有序的,我们应该充分利用这里面的信息,类似于二分查找,也是充分利用了“有序”。
假设A和B的元素个数都大于k/2 ,我们将A的第k/2 个元素(即A[k/2-1]) 和B的第k/2 个元素(即B[k/2-1] )进行比较,有以下三种情况(为了简化这里先假设k 为偶数,所得到的结论对于 k 是奇数也是成立的):
A[k/2-1] == B[k/2-1]
A[k/2-1]> B[k/2-1]
A[k/2-1]< B[k/2-1]
如果A[k/2-1] < B[k/2-1] ,意味着A[0] 到A[k/2-1] 的肯定在A ∪ B的top k元素的范围内,换句话说,A[k/2-1] 不可能大于A ∪ B的第k 大元素。
因此,我们可以放心的删除A数组的这k/2 个元素。同理,当A[k/2-1] >B[k/2-1] 时,可以删除B数组的k/2 个元素。
当A[k/2-1] == B[k/2-1] 时,说明找到了第k 大的元素,直接返回A[k/2-1] 或B[k/2-1] 即可。
因此,我们可以写一个递归函数。那么函数什么时候应该终止呢?
当A或B是空时,直接返回B[k-1] 或A[k-1] ; 当k=1 是,返回min(A[0],B[0]) ;当A[k/2-1]== B[k/2-1] 时 , 返 回A[k/2-1] 或B[k/2-1]
/**
*
* @author dongb
* Median of Two Sorted Arrays
* Binary Chop
* TC O(log(m+n)), SCO(log(m+n))
*
*/
public class Solution {
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int total = nums1.length + nums2.length;
if (total % 2 == 1) {
return findKth(nums1, 0, nums2, 0, total / 2 + 1);
} else {
return (findKth(nums1, 0, nums2, 0, total / 2) +
findKth(nums1, 0, nums2, 0, total / 2 + 1)) / 2.0;
}
}
private static int findKth(int[] nums1, int m, int[] nums2, int n, int k) {
//always assume that nums1 is shorter than nums2 first
// if not, switch nums1 and nums2
if (nums1.length - m > nums2.length - n) {
return findKth(nums2, n, nums1, m, k);
}
if (nums1.length - m == 0) {
return nums2[n + k - 1];
}
if (k == 1) {
return Math.min(nums1[m], nums2[n]);
}
// divide k into two parts
// if the nums1.length is way shorter than nums2.length
// then k/2 is not applicable, use nums1.length - m
int k1 = Math.min(k / 2, nums1.length - m), k2 = k - k1;
if (nums1[m + k1 - 1] < nums2[n + k2 - 1]) {
return findKth(nums1, m + k1, nums2, n, k - k1);
} else if (nums1[m + k1 - 1] > nums2[n + k2 - 1]) {
return findKth(nums1, m, nums2, n + k2, k - k2);
} else {
return nums1[k1 - 1];
}
}
}