/************
** 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.
***********/
Note:
1、把0都移到數組右邊,並保持非零數的順序不變。該題反過來想就是把非0數都按順序移到數組的左邊,這樣就很好理解了。
void moveZeroes(int *nums, int numsSize)
{
int *pZero, *pNoZero;
int *pLast = &nums[numsSize];
pZero = nums;
while (*pZero != 0) // 第一個0的位置
{
if (pZero++ == pLast - 1)
{
return;
}
}
pNoZero = pZero + 1; //從第一個0的下一個開始遍歷
while (pNoZero != pLast)
{
if (*pNoZero != 0)
{
*pZero++ = *pNoZero;
*pNoZero++ = 0;
}
else
{
pNoZero++;
}
}
}