Question:
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)).
code :
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
vector<int> C ;
int i=0,j=0;
for(;i<m&&j<n;)
{
if(A[i]<B[j])
{
C.push_back(A[i]);
i++;
}
else if(A[i]>B[j])
{
C.push_back(B[j]);
j++;
}
else
{
C.push_back(A[i]);
i++;
C.push_back(B[j]);
j++;
}
}
if(i==m)
{
for(;j<n;j++)
C.push_back(B[j]);
}
if(j==n)
{
for(;i<m;i++)
C.push_back(A[i]);
}
double med;
int mid=(m+n)/2;
if((m+n)%2==0)
med = (double)(C[mid]+C[mid-1])/2;
else
med = C[mid];
return med;
}
};