C++ O(n) two pointers concise solution


  • 0
    S
    void moveZeroes(vector<int>& nums) {
        int n = nums.size();
        int first = -1;
        for(int i = 0; i < n; ++i)
        {
            if(nums[i] != 0)
            {
                ++first;
                nums[first] = nums[i];
            }
        }
        
        for(int i = first + 1 ; i < n; ++i)
            nums[i] = 0;
    }

  • 0
    T

    This is not 1 pass. Erasing in the middle of a vector is O(n). Your alg is O(n^2)


  • 0
    S

    Thanks for the note. I updated the code & title accordingly


Log in to reply
 

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