标签:
[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)).
[Analysis]
由于两个数组已经是有序的,这题考的是如何将Linear复杂度优化到Log复杂度。那么很容易就能想到二分法或者说分治算法(Divide and Conquer)。这题我的思路是利用一般的在有序数组里找第K个元素的方法,来找到中数。需要注意的是中数可能是两个数的平均值。基本上难点在于思路的转化以及小心地将递归的所有情况列出来。
[Solution]
public class Solution { public double findMedianSortedArrays(int A[], int B[]) { int m = A.length; int n = B.length; if ((m + n) % 2 == 0) { int median1 = findKSortedArrays(A, 0, m, B, 0, n, (m + n)/2); int median2 = findKSortedArrays(A, 0, m, B, 0, n, (m + n)/2 + 1); return 1.0 * (median1 + median2)/2; } else { return 1.0 * findKSortedArrays(A, 0, m, B, 0, n, (m + n)/2 + 1); } } public int findKSortedArrays(int A[], int lowerA, int upperA, int B[], int lowerB, int upperB, int k) { int m = upperA - lowerA; int n = upperB - lowerB; if (m <= 0) { return B[lowerB + k - 1]; } if (n <= 0) { return A[lowerA + k - 1]; } if (k == 1) { return A[lowerA] < B[lowerB]? A[lowerA] : B[lowerB]; } int midA = (lowerA + upperA - 1) / 2; // (upperA - 1 - lowerA) / 2 + lowerA int midB = (lowerB + upperB - 1) / 2; if (A[midA] <= B[midB]) { if (midA - lowerA + midB - lowerB + 2 <= k) { return findKSortedArrays(A, midA + 1, upperA, B, lowerB, upperB, k - (midA - lowerA + 1)); } else { return findKSortedArrays(A, lowerA, upperA, B, lowerB, midB, k); } } else { if (midA - lowerA + midB - lowerB + 2 <= k) { return findKSortedArrays(A, lowerA, upperA, B, midB + 1, upperB, k - (midB - lowerB + 1)); } else { return findKSortedArrays(A, lowerA, midA, B, lowerB, upperB, k); } } } }
LeetCode #4 Median of Two Sorted Arrays (H)
标签:
原文地址:http://www.cnblogs.com/zhangqieyi/p/4850515.html