使用 C++,求解使数组中所有元素变成 0 所需的最少操作次数。
问题陈述
给定一个大小为 N 的数组,其中每个元素要么为 1,要么为 0。任务是计算使所有元素都变成 0 所需的最少操作次数。可以执行以下操作 −
如果某个元素为 1,则可以将其值更改为 0,那么 −
如果相邻的下一个元素是 1,它会自动转换为 0
如果相邻的下一个元素已经是 0,则不会发生任何事。
If arr[] = {1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1} then 4
operation are required to make all elements zero算法
1.If the current element is 1 then increment the count and search for the next 0 as all consecutive 1’s will be automatically converted to 0. 2. Return final count
示例
#include <iostream>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
int performMinOperation(int *arr, int n){
int i, cnt = 0;
for (i = 0; i < n; ++i) {
if (arr[i] == 1) {
int j;
for (j = i + 1; j < n; ++j) {
if (arr[j] == 0) {
break;
}
}
i = j - 1;
++cnt;
}
}
return cnt;
}
int main(){
int arr[] = {1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1};
cout << "Minimum required operations = " << performMinOperation(arr, SIZE(arr)) << endl;
return 0;
}输出
当编译并执行上述程序时,它会生成以下输出 −
Minimum required operations = 4
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP