给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
//方法1:从前遍历,遇到不为0的往前放,然后将后面的数置为0
void moveZeroes(int* nums, int numsSize) {
int j=0;
int k;
for(int i=0;i<numsSize;i++){
if(nums[i]!=0){
nums[j++]=nums[i];
}
}
for(;j<numsSize;j++){
nums[j]=0;
}
return nums;
}
//方法2:从后面记录末尾第一个不为0的位置rear,然后从后遍历,记录0的位置为token,
//将token与rear之间的数往前移动一个,将尾巴rear置为0,然后尾巴往前走一步
void moveZeroes(int* nums, int numsSize) {
int token;//记录该0的位置
int rear=numsSize-1;//记录末尾第一个非0的位置
int j;
for(int i = numsSize-1; i >= 0; i--)
{
token = i;
if(0 == nums[i])
{
j = rear-i;
while(j--)
{
nums[token] = nums[token+1];
token++;
}
nums[rear] = 0;
rear -= 1;
}
}
}