rustgym/leetcode/
_1089_duplicate_zeros.rs1struct Solution;
2
3impl Solution {
4 fn duplicate_zeros(arr: &mut Vec<i32>) {
5 let n = arr.len();
6 let m = arr.iter().filter(|&x| *x == 0).count();
7 let mut i = n - 1;
8 let mut j = m + n - 1;
9 while i > 0 {
10 if arr[i] != 0 {
11 if j < n {
12 arr[j] = arr[i];
13 }
14 i -= 1;
15 j -= 1;
16 } else {
17 if j < n {
18 arr[j] = 0;
19 }
20 i -= 1;
21 j -= 1;
22 if j < n {
23 arr[j] = 0;
24 }
25 j -= 1;
26 }
27 }
28 if arr[i] != 0 {
29 arr[j] = arr[i];
30 } else {
31 arr[j] = 0;
32 j -= 1;
33 arr[j] = 0;
34 }
35 }
36}
37
38#[test]
39fn test() {
40 let mut arr = vec![1, 0, 2, 3, 0, 4, 5, 0];
41 let res = vec![1, 0, 0, 2, 3, 0, 0, 4];
42 Solution::duplicate_zeros(&mut arr);
43 assert_eq!(arr, res);
44}