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)).
返回两个排序数组的中位数。这个题可以有以下几个思路:
首先可以想到的是将两个数组merge起来,然后返回其中位数。
第二个是,类似merge的思想加上计数,找到(m+n)/2个数或者其前后的数,这个就可以算出中位数。这个方法对于各种情况需要一一考虑到。
第三个,假设A[k/2-1]<B[k/2-1],那么A[k/2-1]之前的数一定在整个有序数列中(m+n)/2之前。
这里我给出后面两种思路的代码。
class Solution { public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int len = m+n; if(len & 0x1){ return findkth(A, m, B, n, len/2 +1); }else{ return ( findkth(A, m, B, n, len/2) + findkth(A, m, B, n, len/2+1) )/2.0; } } double findkth(int A[], int m, int B[], int n, int k){ if(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]); int Aindex = min(m, k/2); int Bindex = k-Aindex; if(A[Aindex-1] < B[Bindex-1]){ return findkth(A+Aindex, m-Aindex, B, n, k-Aindex); } else if(A[Aindex-1] > B[Bindex-1]){ return findkth(A, m, B+Bindex, n-Bindex, k-Bindex); } else{ return A[Aindex-1]; } } };
class Solution { public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int ret = -1; if((A==NULL && B==NULL) || m<0 || n<0) return (double)ret; if(A==NULL || m<=0){ if(n & 1) return (double)B[n/2]; else{ return (double)(B[n/2]+B[n/2-1]) / 2.0; } } if(B==NULL || n<=0){ if(m & 1) return (double)A[m/2]; else{ return (double)(A[m/2]+A[m/2-1]) / 2.0; } } int mid = (m+n)/2; int pre = 0; int i=0, j=0; int count=0; int token = 0; while(i<m && j<n){ if(A[i]<=B[j]){ if(count!=mid) pre = A[i]; if(count==mid){ token = A[i];++count; break; } ++i; }else{ if(count!=mid) pre = B[j]; if(count==mid){ token = B[j];++count; break; } ++j; } ++count; } if(count<=mid){ if(i<m){ if(count==mid){ token = A[i]; }else{ while(count<mid){ pre = A[i++]; ++count; } token = A[i]; } } if(j<n){ if(count==mid){ token = B[j]; }else{ while(count<mid){ pre = B[j++]; ++count; } token = B[j]; } } } if((m+n) & 1 ){ //odd return (double)(token); } else{ //even return (double)(pre+token)/2.0; } } };
参考
http://blog.csdn.net/yutianzuijin/article/details/11499917
-----------------------------------------------------------------------------------------------------------------------------------
[LeetCode] Median of Two Sorted Arrays [16],布布扣,bubuko.com
[LeetCode] Median of Two Sorted Arrays [16]
原文:http://blog.csdn.net/swagle/article/details/29197389