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)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
public:
    void moveZeroes(vector<int> &nums) {
        const int n = nums.size();
        int write = 0;
        for (int read = 0; read < n; ++read) {
            if (nums[read] != 0) {
                nums[write++] = nums[read];
            }
        }

        while (write < n) {
            nums[write++] = 0;
        }
    }
};
comments powered by Disqus