Created
June 4, 2021 18:21
-
-
Save snewcomer/aa858071696b0a2b0c6a7b041f7929fa to your computer and use it in GitHub Desktop.
Rust Sort 0's to back
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Your last Rust code is saved below: | |
fn move_to_back(v: &Vec<u32>) -> Vec<u32> { | |
// extra memory | |
let mut res = vec![]; | |
let mut num_of_zeros = 0; | |
for i in v.iter() { | |
if *i != 0 as u32 { | |
res.push(*i); | |
} else { | |
num_of_zeros += 1; | |
} | |
} | |
res.sort(); | |
while num_of_zeros != 0 { | |
res.push(0 as u32); | |
num_of_zeros -= 1; | |
} | |
res | |
} | |
fn move_to_back_in_place(v: &mut Vec<u32>) -> Vec<u32> { | |
v.sort(); | |
// if value in vector is 0, we will mark this as sorted last (ascending) | |
v.sort_by_key(|a| *a == 0); | |
v.to_vec() | |
} | |
fn main() { | |
let input = vec![1, 0, 0, 2, 3, 4, 0, 6]; | |
let res = move_to_back(&input); | |
dbg!(res); | |
let input = vec![1, 2, 3, 4, 8, 6]; | |
let res = move_to_back(&input); | |
dbg!(res); | |
let mut input = vec![1, 0, 0, 2, 3, 4, 8, 6, 0]; | |
let res = move_to_back_in_place(&mut input); | |
dbg!(res); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment