题目
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.
标签
Array、Two Pointers
难度
简单
分析
题目意思是给定一个整型数组,将数组里面的零全部挪到最后,其余数字保持原来的顺序。解题思路是利用双指针的思想,p(主要用于指向零的),q(主要用于指向非零项),当*p=0,*q!=0时,就需要交换p/q的值,主要判断条件有以下四种:
*p=0;*q=0;
则q++;*p=0;*q!=0;
则*p=*q;
*q = 0;
p++;
q++;*p!=0;*q=0;
则p++;q++;- *p!=0;*q!=0;
则p++;q++;
主要的零和非零之间的替换在条件2处理,条件3、4可以合成一个条件。
C代码实现
void moveZeroes(int* nums, int numsSize) {
int *p, *q;
p = nums;
q = nums;
while(q<nums+numsSize)
{
if(0 == *p)
{
if(0 == *q)
q++;
else
{
*p = *q;
*q = 0;
p++;
q++;
}
}
else
{
p++;
q++;
}
}
}