From 3738fea7bbc090e8fda4e91ff5c7a57073757643 Mon Sep 17 00:00:00 2001 From: EFanZh Date: Sun, 25 Feb 2024 13:10:54 +0800 Subject: [PATCH] Add problem 2149: Rearrange Array Elements by Sign --- src/lib.rs | 1 + .../iterative.rs | 40 +++++++++++++++++++ .../mod.rs | 21 ++++++++++ 3 files changed, 62 insertions(+) create mode 100644 src/problem_2149_rearrange_array_elements_by_sign/iterative.rs create mode 100644 src/problem_2149_rearrange_array_elements_by_sign/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 2a49cc9b..e597a903 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1459,6 +1459,7 @@ pub mod problem_2138_divide_a_string_into_groups_of_size_k; pub mod problem_2140_solving_questions_with_brainpower; pub mod problem_2144_minimum_cost_of_buying_candies_with_discount; pub mod problem_2148_count_elements_with_strictly_smaller_and_greater_elements; +pub mod problem_2149_rearrange_array_elements_by_sign; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2149_rearrange_array_elements_by_sign/iterative.rs b/src/problem_2149_rearrange_array_elements_by_sign/iterative.rs new file mode 100644 index 00000000..479ca7fa --- /dev/null +++ b/src/problem_2149_rearrange_array_elements_by_sign/iterative.rs @@ -0,0 +1,40 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn rearrange_array(nums: Vec) -> Vec { + let mut result = vec![0; nums.len()]; + let mut positive_index = 0; + let mut negative_index = 1; + + for num in nums { + let index = if num < 0 { + &mut negative_index + } else { + &mut positive_index + }; + + result[*index] = num; + *index += 2; + } + + result + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn rearrange_array(nums: Vec) -> Vec { + Self::rearrange_array(nums) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2149_rearrange_array_elements_by_sign/mod.rs b/src/problem_2149_rearrange_array_elements_by_sign/mod.rs new file mode 100644 index 00000000..c2db40ce --- /dev/null +++ b/src/problem_2149_rearrange_array_elements_by_sign/mod.rs @@ -0,0 +1,21 @@ +pub mod iterative; + +pub trait Solution { + fn rearrange_array(nums: Vec) -> Vec; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + (&[3, 1, -2, -5, 2, -4] as &[_], &[3, -2, 1, -5, 2, -4] as &[_]), + (&[-1, 1], &[1, -1]), + ]; + + for (nums, expected) in test_cases { + assert_eq!(S::rearrange_array(nums.to_vec()), expected); + } + } +}