Move Zeros
Description:
Given an array
nums
, write a function to move all0
's to the end of it while maintaining the relative order of the non-zero elements.EXAMPLE:
given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Solution:
Basic idea is to move all the non-zero elements to the front of the array, and set the elements at the tail to zero.
public class Solution {
public void moveZeroes(int[] nums) {
int j = 0;
int len = nums.length;
for(int i = 0; i < len; i++) {
if(nums[i] != 0) {
nums[j] = nums[i];
j++;
}
}
for(;j < len; j++) {
nums[j] = 0;
}
}
}