给定一个数组 nums
, 编写一个函数将所有 0
移动到它的末尾,同时保持非零元素的相对顺序。
例如, 定义 nums = [0, 1, 0, 3, 12]
,调用函数之后, nums
应为 [1, 3, 12, 0, 0]
。
注意事项:
- 必须在原数组上操作,不要为一个新数组分配额外空间。
- 尽量减少操作总数。
贡献者:
特别感谢 @jianchao.li.fighter 用于添加此问题并创建所有测试用例。
思路:
1.遍历数组,使用双指针。将所有非0数字按顺序移到到前面来,然后后面补0;
2.交换数值。[0, 1, 0, 3, 12]->[1, 0, 0, 3, 12]->[1, 3, 0, 0, 12]->[1, 3, 12, 0, 0],只需要3次交换。
??为什么执行时间还是比第一个多了2ms??
void moveZeroes(int* nums, int numsSize) {
int *pre = nums,*cur = nums ,*end = nums+numsSize-1;
int i;
while(pre<end && cur<end)
{
while(pre<end && *pre!=0){
pre++;
}
if(pre<end)
{
cur = pre+1;
while(cur<end && *cur==0){
cur++;
}
*pre=*cur;
*cur=0;
}
}
}