20ms C++ solution


  • 0
    void moveZeroes(vector<int>& nums) {
        int cnt=0;
        int n=nums.size();
        for(vector<int>::iterator iter=nums.begin(); iter!=nums.end(); )
        {
            if( *iter == 0){
                iter = nums.erase(iter);
                cnt++;
            }
            else
                iter ++ ;
        }
        for(int i=n-cnt;i<n;i++)
            nums.push_back(0);
    }

  • 0
    D

    it's very inefficient. Erase moves remain part of array every time


  • 0
    S

    yes, the complexity of this code is O(n^2). Worst case is a vector full of zeros. In this case every erase will take n operations to complete.


Log in to reply
 

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