Skip to content

Commit

Permalink
Add problem 1968: Array With Elements Not Equal to Average of Neighbors
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 21, 2023
1 parent a7f2961 commit e71ee71
Show file tree
Hide file tree
Showing 3 changed files with 77 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 @@ -1363,6 +1363,7 @@ pub mod problem_1957_delete_characters_to_make_fancy_string;
pub mod problem_1961_check_if_string_is_a_prefix_of_array;
pub mod problem_1962_remove_stones_to_minimize_the_total;
pub mod problem_1967_number_of_strings_that_appear_as_substrings_in_word;
pub mod problem_1968_array_with_elements_not_equal_to_average_of_neighbors;

#[cfg(test)]
mod test_utilities;
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
pub struct Solution;

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

use std::mem;

impl Solution {
pub fn rearrange_array(nums: Vec<i32>) -> Vec<i32> {
let mut nums = nums;
let mut iter = nums.iter_mut();
let prev_1 = iter.next().unwrap();
let mut prev_2 = iter.next().unwrap();
let mut is_decreasing = prev_2 < prev_1;

for value in iter {
if is_decreasing == (value < prev_2) {
mem::swap(prev_2, value);
}

prev_2 = value;
is_decreasing = !is_decreasing;
}

nums
}
}

// ------------------------------------------------------ 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>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
pub mod iterative;

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

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

pub fn run<S: Solution>() {
let test_cases = [&[1, 2, 3, 4, 5] as &[_], &[6, 2, 0, 9, 7]];

for nums in test_cases {
let result = S::rearrange_array(nums.to_vec());

assert_eq!(
test_utilities::unstable_sorted(result.iter().copied()),
test_utilities::unstable_sorted(nums.iter().copied()),
);

let mut prev_1 = i32::MIN;
let mut prev_2 = i32::MIN;

for value in result {
assert_ne!(prev_1 + value, prev_2 << 1);

prev_1 = prev_2;
prev_2 = value;
}
}
}
}

0 comments on commit e71ee71

Please sign in to comment.