move zeroes

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.

思路:

构建一个新的数组,把不等于0的数字放入这个数组,剩下的部分填0,再将新数组copy给原数组。

代码一(0ms -_-):

public class Solution {
    public void moveZeroes(int[] nums) {
        int[] moved = new int[nums.length];
        int index = 0;
        for (int n : nums) {
            if (n != 0) {
                moved[index] = n;
                index += 1;
            }
        }
        if (index < (moved.length - 1)) {
            for (int i = index + 1; i < moved.length; i++) {
                moved[i] = 0;
            }
        }
        System.arraycopy(moved, 0, nums, 0, moved.length);
    }
}