给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序
题目分析:由于题目中要求将0移动到末尾,因此可用if判断是否为0,其次分析移动规律,可采用两个指针进行运算,左边指针指向处理好的数据,即左指针左边均不为0,右指针指向还没有处理的数据,但左右指针中间均为0。代码如下
int swap(int *a,int *b){
int t;
t=*a;
*a=*b;
*b=t
}
void moveVoid(int *nums,int numsSize){
int left=0,right=0;
while(right<numsSize){
if(nums[right]){
swap(nums+left,nums+right);
left++;
}
right++;
}
}