-
Notifications
You must be signed in to change notification settings - Fork 0
/
move-zeroes.rs
111 lines (96 loc) · 2.51 KB
/
move-zeroes.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
struct Solution;
impl Solution {
pub fn impl1(nums: &mut Vec<i32>) {
let mut zero = vec![];
for (i, &v) in nums.iter().enumerate() {
if v == 0 {
zero.push(i);
}
}
let len = zero.len();
for (i, &v) in zero.iter().enumerate() {
nums.remove(v - i);
}
for _ in 0..len {
nums.push(0);
}
}
#[allow(unused)]
pub fn impl2(nums: &mut [i32]) {
for i in 1..nums.len() {
for j in 0..nums.len() - i {
if nums[j] == 0 {
nums[j] = nums[j + 1];
nums[j + 1] = 0;
}
}
}
}
#[allow(unused)]
pub fn impl3(nums: &mut Vec<i32>) {
let len = nums.len();
nums.retain(|&x| x != 0);
nums.resize(len, 0);
}
#[allow(unused)]
pub fn impl4(nums: &mut [i32]) {
let len = nums.len();
let mut left = 0;
let mut right = 0;
while right < len {
if nums[right] != 0 {
nums.swap(right, left);
left += 1;
}
right += 1;
}
}
pub fn move_zeroes(nums: &mut Vec<i32>) {
Solution::impl1(nums)
}
}
fn main() {
let mut nums = vec![0, 1, 0, 3, 12];
Solution::move_zeroes(&mut nums);
println!("{:?}", nums);
}
#[cfg(test)]
mod tests {
use crate::Solution;
#[test]
fn test_impl1() {
let mut nums = vec![0, 1, 0, 3, 12];
Solution::move_zeroes(&mut nums);
assert_eq!(nums, vec![1, 3, 12, 0, 0]);
let mut nums = vec![0];
Solution::move_zeroes(&mut nums);
assert_eq!(nums, vec![0]);
}
#[test]
fn test_impl2() {
let mut nums = vec![0, 1, 0, 3, 12];
Solution::impl2(&mut nums);
assert_eq!(nums, vec![1, 3, 12, 0, 0]);
let mut nums = vec![0];
Solution::impl2(&mut nums);
assert_eq!(nums, vec![0]);
}
#[test]
fn test_impl3() {
let mut nums = vec![0, 1, 0, 3, 12];
Solution::impl3(&mut nums);
assert_eq!(nums, vec![1, 3, 12, 0, 0]);
let mut nums = vec![0];
Solution::impl3(&mut nums);
assert_eq!(nums, vec![0]);
}
#[test]
fn test_impl4() {
let mut nums = vec![0, 1, 0, 3, 12];
Solution::impl4(&mut nums);
assert_eq!(nums, vec![1, 3, 12, 0, 0]);
let mut nums = vec![0];
Solution::impl4(&mut nums);
assert_eq!(nums, vec![0]);
}
}