4. Median of Two Sorted Arrays
二有序数组常用二分法, 要判断数组是否越界, 而数组的题常用递归, 擦半的方法, 比快排的方法, 少一个partition 遍历, 但是还是分成logn 层, Lintcode: Nuts & Bolts Problem
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
关键在于找到合适的比较位置, 准备擦出哪个数组的一半, 防止数组越界
The key point of this problem is to ignore half part of A and B each step recursively by comparing the median of remaining A and B:
if (aMid < bMid) Keep [aRight + bLeft]
else Keep [bRight + aLeft]
As the following: time=O(log(m + n))
public double findMedianSortedArrays(int[] A, int[] B) { int m = A.length, n = B.length; int l = (m + n + 1) / 2; int r = (m + n + 2) / 2; return (getkth(A, 0, B, 0, l) + getkth(A, 0, B, 0, r)) / 2.0; } public double getkth(int[] A, int aStart, int[] B, int bStart, int k) { if (aStart > A.length - 1) return B[bStart + k - 1]; if (bStart > B.length - 1) return A[aStart + k - 1]; if (k == 1) return Math.min(A[aStart], B[bStart]); int aMid = Integer.MAX_VALUE, bMid = Integer.MAX_VALUE; if (aStart + k/2 - 1 < A.length) aMid = A[aStart + k/2 - 1]; if (bStart + k/2 - 1 < B.length) bMid = B[bStart + k/2 - 1]; if (aMid < bMid) return getkth(A, aStart + k/2, B, bStart, k - k/2);// Check: aRight + bLeft else return getkth(A, aStart, B, bStart + k/2, k - k/2);// Check: bRight + aLeft }
这是递归, 按照递归的写法来写, 递归出口, 越界出口和正常出口, 递归输入元素的续写(分情况一直擦最小的k/2),
数组的递归, 常考虑其起始值和结束值. 比较值
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2471/Very-concise-O(log(min(MN)))-iterative-solution-with-detailed-explanation