Why do I get Time Limited Exceeded error with my c++ code?


  • 0
    L
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
        double num1=0.0;
        double num2=0.0;
        if(m<n)
        {
            return findMedianSortedArrays(B,n,A,m);
        }
        if(n==0&&m!=0)
        {
            if(m%2)
            return A[m/2];
            else
            return (double)(A[m/2-1]+A[m/2])/2.0;
        }
        int imin=0;
        int imax=m;
        int tmp=(m+n+1)/2;
        while(imin<=imax)
        {
            int i=(imin+imax)/2;
            int j=tmp-i;
            if(j>0&&i<m&&B[j-1]>A[i])
            {
                imin=i;
            }
            else if(i>0&&j<n&&A[i-1]>B[j])
            {
                imax=i;
            }
           else
           {
                if(i==0)
                num1=B[j-1];
                else if(j==0)
                num1=A[i-1];
                else
                num1=A[i-1]>B[j-1]?A[i-1]:B[j-1];
                if((m+n)%2) //odd number
                return num1;
               if(i==m)
                num2=B[j];
               else if(j==n)
                num2=A[i];
               else
                num2=A[i]>B[j]?B[j]:A[i];
               return (double)(num1+num2)/2.0;
           }
        }
        return 0;
        
    }

  • 0
    L

    I have find the answer.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.