Median of Two Sorted Arrays. inout [], [1]. wrong answer.??


  • 0
    W

    double findMedianSortedArrays(int A[], int m, int B[], int n) {

        int ai = 0, bi = 0, num = 0;
        double ans = 0;
        while(num < (m + n) / 2) {
            ans = (A[ai] <= B[bi] && ai < m)? A[ai++]:B[bi++];
            ++num;
        }
        if((m + n) % 2 == 0)
            ans = (ans + (A[ai] <= B[bi]? A[ai]:B[bi])) / 2.0;
        else
            ans = (A[ai] <= B[bi]? A[ai]:B[bi]);
        return ans;
    }
    

    Input: [], [1]
    Output: 0.00000
    Expected: 1.00000

    I don't konw why there is this err.


  • 0
    R

    For this test case, only the code after else is executed.

    else
    ans = (A[ai] <= B[bi]? A[ai]:B[bi]);
    

    and the while loop is not executed due to num == (m+n)/2 == 0.

    There is a problem that you are accessing first element of A[] while the length of it is supposed to be zero. The A[ai] is out of index. The value is most likely 0, based on your output. It also could be -1218465804 if the array is declared as int A[0];


Log in to reply
 

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