A 20ms Constant Space C++ Solution


  • 0
    Y
    class Solution {
    public:
        void moveZeroes(vector<int>& nums) {
            int left = 0, right = 0;
            while(nums[right] != 0) right++;
            if(right != 0) left = right - 1;
            while(left <= right) {
                while((nums[right] == 0)&&(right < nums.size())) right++;
                if(right >= nums.size()) right--;
                if(nums[left] == 0) {
                    nums[left] = nums[right];
                    nums[right] = 0;
                }
                left++;
            }
        }
    };

  • 0
    L

    I don't get your point, you move right to mark position of first non-zeros element after zeros, then swap with left. However you take a lot of time moving left forward to find zero, which right already found.
    I think this should be simpler:

    • move left to first zero
    • assign left to right
    • move right forward till the end.
    • if right meet non-zero, swap with left, move left forward

  • 0
    Y

    Yes you are right, I have updated the code, thank you very much!


Log in to reply
 

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