Given an unsorted integer array, place all zeros to the end of the array without changing the sequence of non-zero elements. (i.e. [1,3,0,8,12, 0, 4, 0,7] --> [1,3,8,12,4,7,0,0,0])
#include <iostream>
int main()
{
int a[9] = {1, 3, 0, 8, 12, 0, 4, 0, 7};
int first = 0, cur = 0;
for(; cur < 9; cur++)
{
if(a[cur] != 0)
{
a[first] = a[cur];
first++;
}
}
for(; first < 9; first++)
{
a[first] = 0;
}
for(int i = 0; i < 9; i++)
{
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
本文介绍了一种将整数数组中所有零元素移动到数组末尾同时保持非零元素原有顺序的算法实现。通过使用两个指针的方法,有效地完成了元素的重新排列,并通过示例代码展示了具体操作过程。
1093

被折叠的 条评论
为什么被折叠?



