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.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

  1. You must do this in-place without making a copy of the array.

  2. Minimize the total number of operations.

void moveZeroes(vector<int>& nums) { // time: O(n); space: O(1)
    int n = nums.size(), pos = 0;
    for (int i = 0; i < n; ++i) {
        if (nums[i] != 0) {
            nums[pos++] = nums[i];
        }
    }
    while (pos < n) {
        nums[pos++] = 0;
    }
    return;
}
void moveZeroes(vector<int>& nums) { // time: O(n); space: O(1)
    for (int i = 0, j = 0; i < nums.size(); ++i) {
        if (nums[i] != 0) {
            swap(nums[i], nums[j++]);
        }
    } 
}

Last updated

Was this helpful?