题目
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
解题思路
采用快慢双指针的思路,先将非0元素进行前置保存,遍历完成之后将慢指针之后的元素全部置零即为所求,以下是代码:
//快慢双指针实现
void moveZeroes(int* nums, int numsSize)
{
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < numsSize; ++fastIndex)
{
if (nums[fastIndex] != 0)
{
nums[slowIndex++] = nums[fastIndex];
}
}
for (slowIndex; slowIndex < numsSize; ++slowIndex)
{
nums[slowIndex] = 0;
}
}
时间复杂度为O(n),空间复杂度为O(1)