Move Zeroes

Easy

LintCode: http://www.lintcode.com/en/problem/move-zeroes/

LeetCode: https://leetcode.com/problems/move-zeroes/#/description

Question

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.

Notice
a) You must do this in-place without making a copy of the array.
b) Minimize the total number of operations.

Example
Given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Thinking

  • 0 always be moved to the last position
  • Shift all elements
  • Make sure to check current element again.

Review

  • Using Two Pointers
    Move Zeros

Solution

Java (Two pointers)

public class Solution {
    public void moveZeroes(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return;
        }
        for (int i = 0, j = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                int tmp = nums[j];
                nums[j++] = nums[i];
                nums[i] = tmp;
            }
        }
        
    }
}

Java (Two for loop. Not good)

public class Solution {
    /**
     * @param nums an integer array
     * @return nothing, do this in-place
     */
    public void moveZeroes(int[] nums) {
        // Write your code here
        if (nums == null) {
            return;
        }
        int zeroCount = 0;
        for (int i = 0; i < nums.length; i++) {
            if ((i + zeroCount) == nums.length) {
                break;
            }
            if (nums[i] == 0) {
                for (int j = i; j < nums.length - 1; j++) {
                    nums[j] = nums[j + 1];
                }
                nums[nums.length - 1] = 0;
                zeroCount++;
                i--; // check current element again
            }
        }
    }
}