標籤:class blog code java http tar
https://oj.leetcode.com/problems/median-of-two-sorted-arrays/
There are two sorted arrays A and B 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)).
思路1:兩個數組進行merge操作,雖然不符合題目要求,但竟然拿可以過(有人說排序之後取中間的也能過。。)。複雜度O(m+n)。
思 路2(參考討論區某大神):使用二分尋找,時間複雜度為log(m+n). 該方法的核心是將原問題轉變成一個尋找第k小數的問題(假設兩個原序列升序排列),這樣中位元實際上是第(m+n)/2小的數。所以只要解決了第k小數的 問題,原問題也得以解決。首先假設數組A和B的元素個數都大於k/2,我們比較A[k/2-1]和B[k/2-1]兩個元素,這兩個元素分別表示A的第k /2小的元素和B的第k/2小的元素。這兩個元素比較共有三種情況:>、<和=。如果A[k/2-1]<B[k/2-1],這表示 A[0]到A[k/2-1]的元素都在A和B合并之後的前k小的元素中。換句話說,A[k/2-1]不可能大於兩數組合并之後的第k小值,所以我們可以將 其拋棄。
double findKth(int a[], int m, int b[], int n, int k){//always assume that m is equal or smaller than nif (m > n)return findKth(b, n, a, m, k);if (m == 0)return b[k - 1];if (k == 1)return min(a[0], b[0]);//divide k into two partsint pa = min(k / 2, m), pb = k - pa;if (a[pa - 1] < b[pb - 1])return findKth(a + pa, m - pa, b, n, k - pa);else if (a[pa - 1] > b[pb - 1])return findKth(a, m, b + pb, n - pb, k - pb);elsereturn a[pa - 1];}class Solution{public:double findMedianSortedArrays(int A[], int m, int B[], int n){int total = m + n;if (total & 0x1)return findKth(A, m, B, n, total / 2 + 1);elsereturn (findKth(A, m, B, n, total / 2)+ findKth(A, m, B, n, total / 2 + 1)) / 2;}};
java改寫:java不支援數組後面元素取址操作,所以有點不方便,要麼每次複製數組的一部分,要麼增加參數,傳入一個本次運算元組的範圍,這裡偷懶採用前一種方案。
public class Solution { public double findMedianSortedArrays(int A[], int B[]) { int total = A.length + B.length; if (total % 2 == 1) return findKth(A, 0, B, 0, total / 2 + 1); else return (findKth(A, 0, B, 0, total / 2) + findKth(A, 0, B, 0, total / 2 + 1)) / 2; } private double findKth(int[] a, int i, int[] b, int j, int k) { if (a.length > b.length) return findKth(b, j, a, i, k); if (a.length == 0) return b[k - 1]; if (k == 1) return Math.min(a[0], b[0]); int pa = Math.min(k / 2, a.length), pb = k - pa; if (a[pa - 1] < b[pb - 1]) return findKth(Arrays.copyOfRange(a, pa, a.length), i + pa, b, j, k - pa); else if (a[pa - 1] > b[pb - 1]) return findKth(a, i, Arrays.copyOfRange(b, pb, b.length), j + pb, k - pb); else return a[pa - 1]; } public static void main(String[] args) { int[] a = new int[] { 1, 3, 5, 7 }; int[] b = new int[] { 2, 4, 6, 8 }; System.out.println(new Solution().findMedianSortedArrays(a, b)); }}
參考:
http://blog.csdn.net/yutianzuijin/article/details/11499917
http://blog.sina.com.cn/s/blog_62fc96e60101f8aa.html