将C++数组中所有零移到开头,所有一移到结尾


在本教程中,我们将编写一个程序,将所有零移到数组的开头,并将所有一移到数组的结尾。

给定一个包含零、一和随机整数的数组。我们需要将所有零移到数组的开头,并将所有一移到数组的结尾。让我们来看一个例子。

输入

arr = [4, 5, 1, 1, 0, 0, 2, 0, 3, 1, 0, 1]

输出

0 0 0 0 4 5 2 3 1 1 1 1

算法

  • 初始化数组。

  • 将索引初始化为**1**。

  • 迭代给定的数组。

    • 如果当前元素不是零,则使用当前元素更新索引处的数值。

    • 递增索引。

  • 编写一个循环,从上面的索引迭代到**n**

    • 将所有元素更新为**1**。

  • 对**0**也同样进行操作。不用增加索引,而是减小索引,将所有零移到数组的开头。

实现

以下是上述算法在C++中的实现

Open Compiler
#include <bits/stdc++.h> using namespace std; void update1And0Positions(int arr[], int n) { int index = 0; for (int i = 0; i < n; i++) { if (arr[i] != 1) { arr[index++] = arr[i]; } } while (index < n) { arr[index++] = 1; } index = 0; for (int i = n - 1; i >= 0; i--) { if (arr[i] == 1) { continue; } if (!index) { index = i; } if (arr[i] != 0) { arr[index--] = arr[i]; } } while (index >= 0) { arr[index--] = 0; } } int main() { int arr[] = { 4, 5, 1, 1, 0, 0, 2, 0, 3, 1, 0, 1 }; int n = 12; update1And0Positions(arr, n); for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; return 0; }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

如果运行以上代码,则会得到以下结果。

0 0 0 0 4 5 2 3 1 1 1 1

更新于:2021年10月25日

707 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告