AC
//Description :There are two sorted arrays A and B of size m and n respectively.Find the median of the two sorted arrays.
//Challenge: The overall run time complexity should be O(log(m + n)).
//part of q532, how to find values in two sorted arrays
/*
* @param A: An integer array
* @param B: An integer array
* @return: a double whose format is *.5 or *.0
*/
double findMedianSortedArrays(vector<int> &A, vector<int> &B) {
// write your code here
int i = A.size(), j = B.size();
vector<int> temp(i+j);
int m=0,n=0,t=0;
while (m<i && n<j) {
if (A[m]>B[n]) temp[t++]=B[n++];
else temp[t++]=A[m++];
}
while (m<i) temp[t++]=A[m++];
while (n<j) temp[t++]=B[n++];
double med;
int index = (i+j)/2;
if ((i+j)%2==0) return (temp[index]+temp[index-1])/2.0;
else return temp[index];
}
网友评论