|
| 1 | +/** |
| 2 | + * [75] Sort Colors |
| 3 | + * |
| 4 | + * Given an array with n objects colored red, white or blue, sort them <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in-place</a> so that objects of the same color are adjacent, with the colors in the order red, white and blue. |
| 5 | + * |
| 6 | + * Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. |
| 7 | + * |
| 8 | + * Note: You are not suppose to use the library's sort function for this problem. |
| 9 | + * |
| 10 | + * Example: |
| 11 | + * |
| 12 | + * |
| 13 | + * Input: [2,0,2,1,1,0] |
| 14 | + * Output: [0,0,1,1,2,2] |
| 15 | + * |
| 16 | + * Follow up: |
| 17 | + * |
| 18 | + * |
| 19 | + * A rather straight forward solution is a two-pass algorithm using counting sort.<br /> |
| 20 | + * First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. |
| 21 | + * Could you come up with a one-pass algorithm using only constant space? |
| 22 | + * |
| 23 | + * |
| 24 | + */ |
| 25 | +pub struct Solution {} |
| 26 | + |
| 27 | +// submission codes start here |
| 28 | + |
| 29 | +// three-way partition |
| 30 | +impl Solution { |
| 31 | + pub fn sort_colors(nums: &mut Vec<i32>) { |
| 32 | + if nums.is_empty() { return } |
| 33 | + let (mut lower_idx, mut upper_idx) = (0_usize, nums.len()-1); |
| 34 | + let mut i = 0_usize; |
| 35 | + while i <= upper_idx { |
| 36 | + if nums[i] < 1 { |
| 37 | + // lower_idx <= i, we've scanned it so we know nums[lower_idx] <= 1, i++ |
| 38 | + nums.swap(lower_idx, i); |
| 39 | + i += 1; lower_idx += 1; |
| 40 | + } else if nums[i] > 1 { |
| 41 | + nums.swap(upper_idx, i); |
| 42 | + if upper_idx < 1 { break } |
| 43 | + upper_idx -= 1; |
| 44 | + } else { |
| 45 | + i += 1; |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +// submission codes end |
| 52 | + |
| 53 | +#[cfg(test)] |
| 54 | +mod tests { |
| 55 | + use super::*; |
| 56 | + |
| 57 | + #[test] |
| 58 | + fn test_75() { |
| 59 | + let mut vec = vec![1,2,0,1,2,2,2,0,0,0,2,1,1,2,0,1,2,2,1,1,0]; |
| 60 | + Solution::sort_colors(&mut vec); |
| 61 | + assert_eq!(vec, vec![0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2]); |
| 62 | + |
| 63 | + let mut vec = vec![]; |
| 64 | + Solution::sort_colors(&mut vec); |
| 65 | + assert_eq!(vec, vec![]); |
| 66 | + |
| 67 | + let mut vec = vec![2,2,2]; |
| 68 | + Solution::sort_colors(&mut vec); |
| 69 | + assert_eq!(vec, vec![2,2,2]); |
| 70 | + } |
| 71 | +} |
0 commit comments