思路:归并排序只做前面(m+n)/2个元素,复杂度是O(m+n)的,听说《算法导论》上面有介绍O(log(n+m))的方法,到时候再看吧
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int *C = new int[m+n];
int i=0, j=0, k = 0;
for(; k *2 <= m + n;){
if(i<m && j < n && A[i] > B[j]){
C[k++] = B[j];
j++;
}
else if(i<m && j < n && A[i] <= B[j]){
C[k++] = A[i];
i++;
}
else break;
}
if(i >= m)
for(;k * 2 <= m+n;){C[k++] = B[j++];}
if(j >= n)
for(;k * 2 <= m+n;){C[k++] = A[i++];}
if((m + n) % 2 == 0)return (C[k-1] + C[k-2])*1.0/2;
else
return C[k-1]*1.0;
}
};