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.
void moveZeroes(int* nums, int numsSize) {
int i=0, j=0;
while(i<numsSize) {
if(nums[i]!=0) {
if(i!=j) {
nums[j] = nums[i];
nums[i] = 0;
j++;
} else {
j++;
}
}
i++;
}
}
我也是看了大神的才写出来的,觉得很巧妙,主要思路是维持两个pointer i 和 j,在没有遇到0时两个一起移动,遇到0时 j 不动 i 后移,i 在遇到非0数时将 i 和 j 的值调换。