Skip to content

Instantly share code, notes, and snippets.

@susliko
Created April 4, 2020 16:23
Show Gist options
  • Save susliko/363846d1a9fbcccb6d408a3f079930ca to your computer and use it in GitHub Desktop.
Save susliko/363846d1a9fbcccb6d408a3f079930ca to your computer and use it in GitHub Desktop.
struct Solution {}
impl Solution {
pub fn move_zeroes(nums: &mut Vec<i32>) {
let mut next_zero_opt: Option<usize> = None;
for i in 0..nums.len() {
let num = nums[i];
if num != 0 && next_zero_opt.is_some() {
let next_zero = next_zero_opt.unwrap();
nums[next_zero] = num;
nums[i] = 0;
let new_zero_opt = nums[next_zero + 1 .. nums.len()]
.iter()
.enumerate()
.find(|(_i, num)| **num == 0)
.map(|(i, _num)| i + next_zero + 1);
next_zero_opt = new_zero_opt;
} else if num == 0 && next_zero_opt.is_none() {
next_zero_opt = Some(i);
}
}
}
fn main() {
let mut ints = vec![0,1,0,3,12];
Solution::move_zeroes(&mut ints);
print!("{:?}", ints);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment