Move Zeroes
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.
1、自己代码
void moveZeroes(int* nums, int numsSize) { int i = 0, j = 0; if(numsSize < 2) return; while(j < numsSize - 1) { while(nums[i] != 0) ++i; j = i + 1; if(j > numsSize - 1) //这里 return; while(nums[j] == 0) ++j; if (j > numsSize - 1) //还有这里,要处理j时,都要检测是否超出了数组范围 return; nums[i] = nums[j]; nums[j] = 0; } }
- 一看就知道写的不是很好,重复代码太多
2、网上代码:把非0的值全部压缩到前面,然后后面的值全部清0;
void moveZeroes(int* nums, int numsSize) { int pos = 0; for(int i = 0; i < numsSize; i++) { if(nums[i] != 0) { nums[pos] = nums[i]; pos++; } } for(; pos < numsSize; pos++) nums[pos] = 0; }