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:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

Solution:

  1. public class Solution {
  2. public void moveZeroes(int[] nums) {
  3. int i = 0, j = 0;
  4. while (j < nums.length) {
  5. if (nums[j] != 0) {
  6. swap(nums, i++, j);
  7. }
  8. j++;
  9. }
  10. }
  11. void swap(int[] nums, int i, int j) {
  12. int tmp = nums[i];
  13. nums[i] = nums[j];
  14. nums[j] = tmp;
  15. }
  16. }