您的位置:首页 > 其它

把零移动到数组的一端 Move all zeroes to end of array

2014-11-29 10:57 369 查看
把零移动到数组的一端 Move all zeroes to end of array

给定一个数组,把数组中所有的 0 移动到数组的右端,并保持其他非零元素的相对顺序。例如数组 {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, 把 0 移动到右端,并保持相对顺序,结果是{1,
9, 8, 4, 2, 7, 6, 0, 0, 0, 0}.下面给出一个O(n)算法,空间复杂度是O(1).

思路:Traverse
the given array ‘arr’ from left to right. While traversing, maintain count of non-zero elements in array. Let the count be ‘count’. For every non-zero element arr[i], put the element at ‘arr[count]’ and increment ‘count’. After complete traversal, all non-zero
elements have already been shifted to front end and ‘count’ is set as index of first 0. Now all we need to do is that run a loop which makes all elements zero from ‘count’ till end of the array.

代码:

// A C++ program to move all zeroes at the end of array
#include <iostream>
using namespace std;

// Function which pushes all zeros to end of an array.
void pushZerosToEnd(int arr[], int n)
{
int count = 0;  // Count of non-zero elements

// Traverse the array. If element encountered is non-zero, then
// replace the element at index 'count' with this element
for (int i = 0; i < n; i++)
if (arr[i] != 0)
arr[count++] = arr[i]; // here count is incremented

// Now all non-zero elements have been shifted to front and 'count' is
// set as index of first 0. Make all elements 0 from count to end.
while (count < n)
arr[count++] = 0;
}

// Driver program to test above function
int main()
{
int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9};
int n = sizeof(arr) / sizeof(arr[0]);
pushZerosToEnd(arr, n);
cout << "Array after pushing all zeros to end of array :\n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: