|
| 1 | +// 75. Sort Colors, Medium |
| 2 | +// https://leetcode.com/problems/sort-colors/ |
| 3 | +impl Solution { |
| 4 | + pub fn sort_colors(nums: &mut Vec<i32>) { |
| 5 | + let n = nums.len(); |
| 6 | + if n <= 1 { |
| 7 | + return; |
| 8 | + } |
| 9 | + |
| 10 | + let mut swapped = true; |
| 11 | + |
| 12 | + while swapped { |
| 13 | + swapped = false; |
| 14 | + for i in 0..n - 1 { |
| 15 | + if nums[i] > nums[i + 1] { |
| 16 | + nums.swap(i, i + 1); |
| 17 | + swapped = true; |
| 18 | + break; |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +struct Solution {} |
| 26 | + |
| 27 | +#[cfg(test)] |
| 28 | +mod tests { |
| 29 | + use super::*; |
| 30 | + use crate::{vec_string, vec_vec_i32, vec_vec_string}; |
| 31 | + |
| 32 | + #[test] |
| 33 | + fn test_sort_colors() { |
| 34 | + let mut colors = vec![2, 0, 2, 1, 1, 0]; |
| 35 | + Solution::sort_colors(&mut colors); |
| 36 | + assert_eq!(colors, vec![0, 0, 1, 1, 2, 2]); |
| 37 | + } |
| 38 | + |
| 39 | + #[test] |
| 40 | + fn test_sort_colors2() { |
| 41 | + let mut colors = vec![2, 0, 1]; |
| 42 | + Solution::sort_colors(&mut colors); |
| 43 | + assert_eq!(colors, vec![0, 1, 2]); |
| 44 | + } |
| 45 | + |
| 46 | + #[test] |
| 47 | + fn test_sort_colors3() { |
| 48 | + let mut colors = vec![0]; |
| 49 | + Solution::sort_colors(&mut colors); |
| 50 | + assert_eq!(colors, vec![0]); |
| 51 | + } |
| 52 | + |
| 53 | + #[test] |
| 54 | + fn test_sort_colors4() { |
| 55 | + let mut colors = vec![1]; |
| 56 | + Solution::sort_colors(&mut colors); |
| 57 | + assert_eq!(colors, vec![1]); |
| 58 | + } |
| 59 | +} |
0 commit comments