Straightforward 3ms C++ solution


  • 0
    B

    The idea is really straightforward. Use ptr to find the next value that not equals to val. Copy it to the next place in nums until ptr reaches the end.

    int removeElement(vector<int>& nums, int val)
    {
        int n = nums.size();
        int ptr = 0, i = 0;
        for(; i < n; ++i)
        {
            while(ptr < n && nums[ptr] == val) ptr++;   //Find next element whose value is not val.
            if(ptr == n) break;
            nums[i] = nums[ptr++];
        }
        return i;
    }

Log in to reply
 

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