Skip to content

Commit

Permalink
Added sort colors solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Jun 12, 2024
1 parent 156ddcc commit 55d4b11
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ other languages.
- Sum Root to Leaf (https://leetcode.com/problems/sum-root-to-leaf-numbers)
- Repeated DNA Sequence (https://leetcode.com/problems/repeated-dna-sequences/)
- Rotate Array (https://leetcode.com/problems/rotate-array/)
- Sort Colors (https://leetcode.com/problems/sort-colors)

### Other

Expand Down
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,4 @@ mod third_max;
mod two_sum;
mod unique_occurrences;
mod zero_or_one;
mod sort_colors;
40 changes: 40 additions & 0 deletions src/leetcode/sort_colors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
pub fn sort_colors(numbers: &mut [i32]) {
let counts = numbers.iter().fold((0, 0, 0), |mut acc, curr| {
match curr {
0 => acc.0 += 1,
1 => acc.1 += 1,
2 => acc.2 += 1,
_ => {}
}
acc
});

let mut index = 0;
for _ in 0..counts.0 {
numbers[index] = 0;
index += 1;
}
for _ in 0..counts.1 {
numbers[index] = 1;
index += 1;
}
for _ in 0..counts.2 {
numbers[index] = 2;
index += 1;
}
}

#[cfg(test)]
mod tests {
use std::vec;

use crate::leetcode::sort_colors::sort_colors;

#[test]
fn test_sort_colors() {
let mut numbers = vec![0, 1, 2, 0, 1, 2];
sort_colors(&mut numbers);

assert_eq!(&vec![0, 0, 1, 1, 2, 2], &numbers);
}
}

0 comments on commit 55d4b11

Please sign in to comment.