Skip to content

Commit

Permalink
Add problem 2149: Rearrange Array Elements by Sign
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Feb 25, 2024
1 parent 15f567d commit 3738fea
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
40 changes: 40 additions & 0 deletions src/problem_2149_rearrange_array_elements_by_sign/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn rearrange_array(nums: Vec<i32>) -> Vec<i32> {
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<i32>) -> Vec<i32> {
Self::rearrange_array(nums)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
21 changes: 21 additions & 0 deletions src/problem_2149_rearrange_array_elements_by_sign/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
pub mod iterative;

pub trait Solution {
fn rearrange_array(nums: Vec<i32>) -> Vec<i32>;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
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);
}
}
}

0 comments on commit 3738fea

Please sign in to comment.