(C++) OJ truncating my output?


  • 0
    J

    My C++ code is:

        int removeElement(int A[], int n, int elem) {
        for(int i=0; i<n; i++) {
            while(A[i] == elem) {
                A[i] = A[n-1];
                n--;
            }
        }
        return n;
    }
    

    But, when the OJ is saying it will not work in (at least) this case:

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

    Seems like the return value truncated - it just shows the closing square bracket. I am pretty sure I am returning n=0 in this case and from what I read of the question, a correct 'n' and values within array A[] of which that ends up concerning (nothing beyond the new length...).

    Am I missing something or should OJ pass this? Thanks.


  • 0
    S

    Well I am pretty sure you won't return 0 in the above test case. Look at this part:

    while(A[i] == elem) {
            A[i] = A[n-1];
            n--;
        }
    

    when n == 1, elem == 1, and A[0] == 1. In the first iteration, you assign A[0] to A[0], then decrement n by 1. At this point, we still have A[0] == elem, so this loop will be executed AT LEAST TWICE, and n will be AT MOST -1. The negative value would mess up the output.


  • 0
    J

    Ah, thanks - I should have questioned myself harder!


Log in to reply
 

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