Move Zeroes
Question (LC.283)
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: nums = [0, 1, 0, 3, 12]
Output: nums = [1, 3, 12, 0, 0]
Analysis
Store a count for zero shift every up then pad zeroes. The tricky park is how to count and shift.
Code
public void moveZeroes(int[] nums) {
// count zeroes and shift non-zeroes
int count_zeroes = 0;
for (int x = 0; x < nums.length; x++) {
if (nums[x] == 0) count_zeroes++;
else nums[x - count_zeroes] = nums[x];
}
// pad zeroes
for (int y = count_zeroes; y > 0; y--)
nums[nums.length - y] = 0;
}