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)).
有两个有序的数组,找出这两数组整合后的中位数,要求时间复杂度O(nlogn)
要找这两个排序数组的中位数,数组长度分别是Len(A)=m和Len(B)=n
class Solution { public: double getKth(int A[], int B[], int m, int n, int k){ if(m>n) return getKth(B, A, n, m, k); if(m==0) return B[k-1]; if(k==1) return min(A[0], B[0]); int pa = min(m, k/2), pb = k - pa; if(A[pa-1] < B[pb-1]){ return getKth(A+pa, B, m-pa, pb, k-pa); } else if(A[pa-1] > B[pb-1]){ return getKth(A, B+pb, pa, n-pb, k-pb); } else return A[pa-1]; } double findMedianSortedArrays(int A[], int m, int B[], int n) { double median = 0; if((m+n)%2==1){ median = getKth(A, B, m, n, (m+n+1)/2); } else{ median = (getKth(A, B, m, n, (m+n)/2) + getKth(A, B, m, n, (m+n)/2+1))/2; } return median; } };
leetCode-002 Median of Two Sorted Arrays,布布扣,bubuko.com
leetCode-002 Median of Two Sorted Arrays
原文地址:http://blog.csdn.net/harryhuang1990/article/details/25711805