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


  • 0
    C

    class Solution {
    public:
    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
                    --newlength;
                    // Decrease the index so that the new current element
                    // can be checked in next loop
                    --index;
                }
                else
                    --newlength;
            }
        }
        return newlength;
    }
    

    };


Log in to reply
 

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