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.

Rust Solution

struct Solution;

impl Solution {
    fn move_zeroes(nums: &mut Vec<i32>) {
        let mut j = 0;
        for i in 0..nums.len() {
            let x = nums[i];
            if x != 0 {
                nums[i] = 0;
                nums[j] = x;
                j += 1;
            }
        }
    }
}

#[test]
fn test() {
    let mut nums = vec![0, 1, 0, 3, 12];
    Solution::move_zeroes(&mut nums);
    assert_eq!(nums, vec![1, 3, 12, 0, 0]);
}

Having problems with this solution? Click here to submit an issue on github.