1089.cpp (649B)
1 class Solution { 2 public: 3 void duplicateZeros(vector<int> &arr) { 4 int cnt = 0; 5 int len = arr.size() - 1; 6 for (int i = 0; i + cnt <= len; i++) 7 if (arr[i] == 0) { 8 if (i + cnt == len) { 9 arr[len] = 0; 10 len -= 1; 11 break; 12 } 13 cnt++; 14 } 15 16 for (int i = len - cnt; i >= 0; i--) { 17 if (arr[i] == 0) { 18 arr[i + cnt] = 0; 19 cnt--; 20 arr[i + cnt] = 0; 21 } else { 22 arr[i + cnt] = arr[i]; 23 } 24 } 25 } 26 };