Solve the problem that if the elem is the last of A

  • 0

    class Solution {
    int removeElement(int A[], int n, int elem) {
    if(n==0) return 0;

        int newlength = n;
        for(int index=0; index != newlength; index++)
            if(A[index] == elem)    
                //if elme is not the last of A
                if(index != newlength)
                    A[index] = A[newlength-1];
                    //Use the last element to cover the current element
                    //And decrease the newLength by 1
                    // Decrease the index so that the new current element
                    // can be checked in next loop
        return newlength;


Log in to reply

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