add: 220617-CN

This commit is contained in:
Eat-Swap 2022-06-17 00:51:24 +08:00
parent 7d9b13b6b5
commit bfda3b662f
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 32 additions and 1 deletions

31
cpp/2206/220617-CN.cpp Normal file
View File

@ -0,0 +1,31 @@
#include <vector>
/**
* 1089. Duplicate Zeros
* Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.
* Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.
*/
class Solution {
public:
static void duplicateZeros(std::vector<int>& arr) {
const int n = arr.size();
int pos = 0, ori = 0;
for (; ori < n; ++pos)
ori += arr[pos] ? 1 : 2;
if (ori > n) { // else: ori == n
arr[ori = n - 1] = 0;
--pos;
}
--pos;
for (; ori; --pos)
if (!(arr[--ori] = arr[pos]))
arr[--ori] = arr[pos];
}
};
int main() {
std::vector<int> s {1,0,2,3,0,4,5,0};
Solution::duplicateZeros(s);
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2206)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2206 220616-CN.cpp) ADD_EXECUTABLE(2206 220617-CN.cpp)