My C++ solution, Any better way? (runtime:20ms, beats:28.88%)


  • 0
    K

    void moveZeroes(vector<int>& nums) {
    if(nums.size() < 2)
    return;
    int pos_pre = 0;
    int pos_tail = 1;

        while(nums[pos_pre] != 0 && pos_pre < nums.size())
            pos_pre++;  //find the first zero pos
    
        if(pos_pre >= nums.size() - 1)
            return;
    
        pos_tail = pos_pre + 1;
        while(nums[pos_tail] == 0)
            pos_tail++; //find the first non-zero pos
    
        while(pos_tail < nums.size())
        {   
            if(nums[pos_tail] != 0)
            {   
                nums[pos_pre++] = nums[pos_tail];   //move the element
            }   
            pos_tail++;
        }   
    
        while(pos_pre < nums.size())
            nums[pos_pre++] = 0;    //handle the last zero
    
    
    }

Log in to reply
 

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