C++ code, which moves as few elements as possible.


  • 0
    L
    class Solution {
    public:
        int removeElement(int A[], int n, int elem) {
            for ( int i=0; i<n; )
            {
                if ( A[n-1] == elem )
                    n--;
                else if ( A[i] != elem )
                    i++;
                else
                    A[i++] = A[(n--)-1];
            }
            return n;
        }
    };

Log in to reply
 

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