[LeetCode] Move Zeroes

/************
** 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++;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章