Given an arraynums
, write a function to move all0
's to the end of it while maintaining the relative order of the non-zero elements.
For example, givennums = [0, 1, 0, 3, 12]
, after calling your function,nums
should be[1, 3, 12, 0, 0]
.
Note:
Credits:
Special thanks to@jianchao.li.fighterfor adding this problem and creating all test cases.
class Solution {
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) return;
int i = 0;
while (i < nums.length && nums[i] != 0){
i++;
}
int j = i;
while (j < nums.length){
if (nums[j] != 0){
swap(nums, i, j);
i++;
}
j++;
}
}
private void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}