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.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should
be [1, 3, 12, 0, 0]
.
基本思想是使用两个指针 一个位于当前数字 一个位于最后一个非0 的数字
public class Solution {
public void moveZeroes(int[] nums) {
int i=0;
int j=0;
for(i = 0; i<nums.length;i++){
if(nums[i]!=0){
if(i!=j){
nums[j++]=nums[i];
nums[i]=0;
}
else{
j++;
}
}
}
}
}