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)).
将两个有序数组合并,注意题目求得是the median of the two sorted array,
当m+n是奇数时返回的是合并后的中间数即C[(m+n)/2]
当m+n是偶数时返回的是合并后的中间两个数的平均数即(C[(m+n)/2]+C[(m+n)/2-1]+0.0)/2
注意题目求的是double,空间复杂度是O(m+n)
#include <iostream> #include <vector> #include <algorithm> using namespace std; double findMedianSortedArrays(int A[], int m, int B[],int n){ int *C = new int[m+n],i=0,j=0,k = 0; while(i < m && j < n ){ if(A[i] > B[j]) C[k++]=B[j++]; else if(A[i] < B[j]) C[k++] = A[i++]; else { C[k++]=A[i++];C[k++] = B[j++];} } if(i < m ){ for(int idx = i ; idx < m ; idx++) C[k++] = A[idx]; } if( j< n){ for(int idx = j; idx < n; idx++) C[k++] = B[idx]; } double mid = double(C[(m+n)/2]); if((m+n)%2 == 0) mid = (C[(m+n)/2]+C[(m+n)/2-1]+0.0)/2; delete [] C; return mid; } int main(){ int A[] ={1,3} ; int B[] = {2}; cout<<findMedianSortedArrays(A,2,B,1)<<endl; }
利用二分查找,时间复杂度O(log(m+n))
#include <iostream> #include <algorithm> using namespace std; double findKth(int A[], int m, int B[], int n , int k){ if(m > n){ return findKth(B,n,A,m,k); }else{ if( m == 0 ) return B[k-1]; if( k == 1 ) return min(A[0],B[0]); int first = min(k/2,m),second = k - first; if( A[first- 1] < B[second-1]) return findKth(A+first,m-first,B,n,k-first); else if(A[first-1] > B[second-1]) return findKth(A,m,B+second,n-second,k-second); else return A[first-1]; } } double findMedianSortedArrays(int A[], int m, int B[], int n){ int total = m + n; if(total & 0x1) return findKth(A,m,B,n,(total>>1)+1); else return (findKth(A,m,B,n,(total>>1)) + findKth(A,m,B,n,(total>>1)+1))/2; } int main(){ int A[] ={1,2,2} ; int B[] = {1,2,3}; cout<<findMedianSortedArrays(A,3,B,3)<<endl; }