From 7d031351fe77a390f37861c978e9dbe048f47ec5 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Tue, 4 Feb 2025 11:36:18 +0800 Subject: [PATCH] 20250204 finished. --- src/problem/mod.rs | 2 + src/problem/p922_sort_array_by_parity_ii.rs | 53 +++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 src/problem/p922_sort_array_by_parity_ii.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 61e8d0c..79d690d 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -468,3 +468,5 @@ mod p81_search_in_rotated_sorted_array_ii; mod p598_range_addition_ii; mod p680_valid_palindrome_ii; + +mod p922_sort_array_by_parity_ii; diff --git a/src/problem/p922_sort_array_by_parity_ii.rs b/src/problem/p922_sort_array_by_parity_ii.rs new file mode 100644 index 0000000..b379cf8 --- /dev/null +++ b/src/problem/p922_sort_array_by_parity_ii.rs @@ -0,0 +1,53 @@ +/** + * [922] Sort Array By Parity II + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn sort_array_by_parity_ii(mut nums: Vec) -> Vec { + let mut last_odd_pos = vec![]; + let mut last_even_pos = vec![]; + + for i in 0..nums.len() { + if i % 2 == 0 && nums[i] % 2 != 0 { + if let Some(pos) = last_even_pos.pop() { + nums.swap(pos, i); + } else { + last_odd_pos.push(i); + } + } + if i % 2 != 0 && nums[i] % 2 == 0 { + if let Some(pos) = last_odd_pos.pop() { + nums.swap(pos, i); + } else { + last_even_pos.push(i); + } + } + } + + nums + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_922() { + assert_eq!( + vec![0, 9, 2, 5, 6, 7, 8], + // 0, 1, 2, 3, 4, 5, 6 + Solution::sort_array_by_parity_ii(vec![0, 8, 2, 6, 5, 7, 9]) + ); + assert_eq!( + vec![4, 5, 2, 7], + Solution::sort_array_by_parity_ii(vec![4, 2, 5, 7]) + ); + assert_eq!(vec![2, 3], Solution::sort_array_by_parity_ii(vec![2, 3])); + } +}