Tests have a bug?


  • 0
    S

    I run the code but the test result shows me next:

    • Input: [1], 1
    • Output: ]
    • Expected: []

    It seems like not the bug in my code (output does not show '[')

    Here is my code

    class Solution {
    public:
        int removeElement(vector<int>& nums, int val)
        {
            int removed = 0;
            
            vector<int>::iterator itCurr = nums.begin();
            vector<int>::iterator itFree = nums.end();
            
            while (itCurr != nums.end())
            {
                // find the first free spot
                if (itFree == nums.end())
                {
                    if (*itCurr == val)
                    {
                        itFree = itCurr;
                        ++removed;
                    }
                    
                    ++itCurr;
                    continue;
                }
                
                // at this point we should have free spot for sure
                if (*itCurr == val)
                {
                    // find next free spot
                    while (*itFree != val)
                        ++itFree;
    
                    // copy value from curr to free
                    *itFree = *itCurr;
                    // make sure curr become a free spot
                    *itCurr = val;
                    // cound the amount of removed
                    ++removed;
                }
                
                ++itCurr;
            }
            
            // remove the tail
            itFree = nums.begin() + (nums.size() - removed);
            nums.erase(itFree, nums.end());
            
            return nums.size() - removed;
        }
    };

Log in to reply
 

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