The tricky part is that the relative order of non-zero values need to be maintained. A straightforward solution:
- traverse the array to find any non-zero value
- move the found value from step 1 to the front of the array using a pointer to keep track of index
- change all the values to zero after the pointer
public static void moveZeroes2(int[] nums) {
if (nums == null || nums.length < 2) return;
int index = 0;
for (int num : nums){
if (num != 0){
nums[index++] = num;
}
}
for (; index < nums.length; index++){
nums[index] = 0;
}
return;
}