C++ solution using swap, 5ms


  • 3
    E

    A straight forward method, one path, put all the elem items to the tail

    Note: watch out the edges.

    int removeElement(int A[], int n, int elem) {
    if(n<1) return n;

     int last=n-1;
    for(int i=0;i<=last;)
    {
        if(A[i]==elem)
        {
            swap(A[i],A[last--]);
        } else
        {
            ++i;
        }
    }
    
    return last+1;
    

    }


Log in to reply
 

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