283 Move Zeroes

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

  • Note: You must do this in-place without making a copy of the array. Minimize the total number of operations.

Solution:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int i = 0, j = 0;
        int n = nums.size();
        while ( i <= n-1 ) {
            if ( nums[i] == 0 ) { i++; continue; }
            nums[j++] = nums[i++];
        }
        while ( j <= n-1 ) nums[j++] = 0;
        return;
    }
};

Notes
Two pointers!

results matching ""

    No results matching ""