[LeetCode] Move Zeroes

来源:互联网 发布:手机android编程软件 编辑:程序博客网 时间:2024/06/16 09:34

/************
** 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++;        }    }}
0 0
原创粉丝点击