C++ 6ms, sequence maintained, and possible implementation of remove() in C++ STL


  • 0
    S
    class Solution {
    public:
        int removeElement(int A[], int n, int elem)
        {
            if (!A) return 0;
            
            int fill = 0, scan = 0;
    
            while (scan < n) {
                while (scan < n && A[scan] == elem)
                    ++scan;
                while (scan < n && A[scan] != elem)
                    A[fill++] = A[scan++];
            }
    
            return fill;
        }
    };
    

    I have read C++ STL remove() function, seeing its result, and come up with this solution.

    Decipher this solution:

    1. Two pointers

    2. One scan from begin to end.

    3. Use latter element to fill previous element, no swap.


  • 0
    E

    Hi, nice code. What do you think is the difference with this one?

    class Solution {
    public:
        int removeElement(int A[], int n, int elem)
        {
            int trailing = 0;
            int leading = 0;
            while (leading < n)
                if (A[leading] == elem) ++leading; else A[trailing++] = A[leading++];
            return trailing;
        }
    };
    

Log in to reply
 

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