I tried something new. Hope you like it! Solution in c++


#1

int odd(const vector &a, const vector &b,int n,int m,int x)
{
int mi = min(a[0], b[0]), ma = max(a[n - 1], b[m - 1]);
while (mi <= ma)
{
int mid = (mi + ma) / 2;
int z = 0;
z = upper_bound(a.begin(),a.end(), mid) - a.begin();
z = z + upper_bound(b.begin(),b.end(), mid) - b.begin();
if (z < x)
{
mi = mid + 1;
}
else
{
ma = mid - 1;
}
}
return mi;
}
double even(const vector &a, const vector &b,int n,int m,int x)
{
int j = odd(a, b,n,m,x);
x++;
int k = odd(a, b,n,m,x);
return double((j + k)*1.00000 / 2);
}
double Solution::findMedianSortedArrays(const vector &a, const vector &b) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details

int n=a.size(),m=b.size(),i,j;
if(n==0)
{
    if(m%2==1)
    {
        return double(b[m/2]);
    }
    else
    {
        return double((b[m/2]+b[m/2-1])*1.0000/2);
    }
}
if(m==0)
{
    if(n%2==1)
    {
        return double(a[n/2]);
    }
    else
    {
        return double((a[n/2]+a[n/2-1])*1.00000/2);
    }
}
double ans=0;
if((n+m)%2==1)
{
    int x=(n+m+1)/2;
    ans=odd(a, b,n,m,x);
}
else
{
    int x=(n+m)/2;
    ans=even(a,b,n,m,x);
}
return ans*1.000000;

}