283. Move Zeroes

1. Description

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.
Note that you must do this in-place without making a copy of the array.

2. Example

Example 1

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

3. Constraints

  • 1 <= nums.length <= $10^4$
  • -$2^{31}$ <= nums[i] <= $2^{31}$ - 1

4. Solutions

Two Pointers

n = nums.size()
Time complexity: O(n)
Space complexity: O(1)

class Solution {
public:
    void moveZeroes(vector<int> &nums) {
        for (int i = 0, last_non_zero = 0; i < nums.size(); ++i) {
            if (nums[i] != 0) {
                swap(nums[i], nums[last_non_zero]);
                ++last_non_zero;
            }
        }
    }
};
comments powered by Disqus