diff --git a/cpp/2206/220617-CN.cpp b/cpp/2206/220617-CN.cpp new file mode 100644 index 0000000..068ed18 --- /dev/null +++ b/cpp/2206/220617-CN.cpp @@ -0,0 +1,31 @@ +#include + +/** + * 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& 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 s {1,0,2,3,0,4,5,0}; + Solution::duplicateZeros(s); + return 0; +} diff --git a/cpp/2206/CMakeLists.txt b/cpp/2206/CMakeLists.txt index 1dc2d09..7871f1c 100644 --- a/cpp/2206/CMakeLists.txt +++ b/cpp/2206/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2206) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2206 220616-CN.cpp) +ADD_EXECUTABLE(2206 220617-CN.cpp)