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]
.
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
从后向前循环,curiser永远指向最后一个不为0的数字的索引,用循环向前遍历,i=curiser前第一个0的索引。每次找到i,则nums[i+1] 到 nums[curiser]向前移动一个,然后nusm[curiser] = 0;
然后curiser会减一(每次执行一次移动,最后一个不为0的数字的的索引向前移动一位,一直指向同一个数字),然后找到前一个i,继续执行,直到完成对数组的遍历。
C代码:
void moveZeroes(int* nums, int numsSize) { int curiser = numsSize - 1; while(nums[curiser] == 0) { curiser--; } int i = curiser; while(i >= 0) { while(nums[i] != 0) { i--; } if(i >= 0) { for(int k = i; k < curiser; k++) { nums[k] = nums[k + 1]; } nums[curiser--] = 0; } else { return; } } }