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:

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

Solution

非零元素按顺序填充数组,余下清零

Complexity

O(N) O(1)

Code

    public void moveZeroes(int[] nums) {
        if(nums == null || nums.length == 0)
            return;
        int idx = 0;
        for(int num : nums){
            if(num != 0){
                nums[idx++] = num;
            }
                
        }
        while(idx < nums.length){
            nums[idx++] = 0;
        }
    }