在 C++ 中将数字翻转为零
假设我们有一个名为 nums 的整数数组,其中包含 0 和 1。假设我们有一种操作,其中我们在 nums 中挑选一个索引 i,并将索引 i 处的元素及所有在 i 右侧的数字翻转。我们必须找出使 nums 中包含所有 0 所需的最少操作数。
因此,如果输入类似于 [1,0,1],则输出将为 3,在索引 0 上的操作,它将转换 [0,1,0],然后在索引 1 上 [0,0,1],然后索引 2,[0,0,0]。
为了解决这个问题,我们将遵循以下步骤:
n := nums 的大小
定义大小为 n 的数组 op
ret := 0
对于将 i 初始化为 0,当 i < nums 的大小时,更新(将 i 递增 1),执行以下操作:
如果 i - 1 >= 0,则:
op[i] := op[i] + op[i - 1]
如果 (nums[i] + op[i]) & 1 非零,则:
(将 op[i] 递增 1)
(将 ret 递增 1)
让我们看看以下实现以便更好地理解:
示例
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int solve(vector<int>& nums) {
int n = nums.size();
vector<int> op(n);
int ret = 0;
for (int i = 0; i < nums.size(); i++) {
if (i - 1 >= 0) {
op[i] += op[i - 1];
}
if ((nums[i] + op[i]) & 1) {
op[i]++;
ret++;
}
}
return ret;
}
};
main() {
Solution ob;
vector<int> v = {1,0,1};
cout << (ob.solve(v));
}输入
{1,0,1}输出
3
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP