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)).
解题思路:
一看算法复杂度,就知道要用binary search, binary search 的本质是本次去一半。
本题的本质是找第K大的数字。本题找中值,则要根据奇偶性判断是两个加起来除2还是中间那个数。
画图解决,取A[k/2-1] 与 B[k/2-1]比较,当然先要判断它们是否存在,如果 A[k/2-1] < B[k/2-1], 那么 A[0]到A[k/2-1]里不存在target, 去掉它们。然后继续比较。
findkth 运用递归,递归的写法注意:先写极端情况,再写一般情况。不然很可能死循环。
注意: k - k/2 != k/2 比如 k=5 k/2 = 2 k/2+k/2 = 4 != 5
java code: 参考九章算法
public class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { //from time complexity, think use binary search int len = nums1.length + nums2.length; if (len % 2 == 1) { return findKth(nums1, 0, nums2, 0, len / 2 + 1); }else { return (findKth(nums1, 0, nums2, 0, len / 2) + findKth(nums1, 0, nums2, 0, len / 2 + 1)) / 2.0; } } //find kth number of two sorted array public int findKth(int[] A, int A_start, int[] B, int B_start, int k) { //deal with boundary case if (A_start >= A.length) { return B[B_start + k - 1]; } if (B_start >= B.length) { return A[A_start + k - 1]; } if (k == 1) { return Math.min(A[A_start], B[B_start]); } //deal with general case int A_key = A_start + k / 2 - 1 < A.length? A[A_start + k / 2 - 1] : Integer.MAX_VALUE; int B_key = B_start + k / 2 - 1 < B.length? B[B_start + k / 2 - 1] : Integer.MAX_VALUE; if(A_key < B_key) { return findKth(A, A_start + k / 2, B, B_start, k - k / 2); }else { return findKth(A, A_start, B, B_start + k / 2, k - k / 2); } } }
Reference:
1. http://www.jiuzhang.com/solutions/median-of-two-sorted-arrays/