From fecac9175c1ddc0055385319683193f68bfa374c Mon Sep 17 00:00:00 2001 From: Spxg Date: Wed, 4 Dec 2024 12:58:05 +0800 Subject: [PATCH] Add problem 0896: Monotonic Array --- src/lib.rs | 1 + src/problem_0896_monotonic_array/iterative.rs | 33 +++++++++++++++++++ src/problem_0896_monotonic_array/mod.rs | 24 ++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 src/problem_0896_monotonic_array/iterative.rs create mode 100644 src/problem_0896_monotonic_array/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 1b13797..0cfad98 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -449,6 +449,7 @@ pub mod problem_0884_uncommon_words_from_two_sentences; pub mod problem_0889_construct_binary_tree_from_preorder_and_postorder_traversal; pub mod problem_0890_find_and_replace_pattern; pub mod problem_0895_maximum_frequency_stack; +pub mod problem_0896_monotonic_array; pub mod problem_0900_rle_iterator; pub mod problem_0915_partition_array_into_disjoint_intervals; pub mod problem_0916_word_subsets; diff --git a/src/problem_0896_monotonic_array/iterative.rs b/src/problem_0896_monotonic_array/iterative.rs new file mode 100644 index 0000000..c6bb72d --- /dev/null +++ b/src/problem_0896_monotonic_array/iterative.rs @@ -0,0 +1,33 @@ +pub struct Solution; + +impl Solution { + pub fn is_monotonic(nums: Vec) -> bool { + let mut prev = nums[0]; + let mut increasing = None; + for &num in &nums[1..] { + match (num.cmp(&prev), increasing) { + (std::cmp::Ordering::Less, None) => increasing = Some(false), + (std::cmp::Ordering::Greater, None) => increasing = Some(true), + (std::cmp::Ordering::Less, Some(true)) + | (std::cmp::Ordering::Greater, Some(false)) => return false, + _ => (), + }; + prev = num; + } + true + } +} + +impl super::Solution for Solution { + fn is_monotonic(nums: Vec) -> bool { + Self::is_monotonic(nums) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_0896_monotonic_array/mod.rs b/src/problem_0896_monotonic_array/mod.rs new file mode 100644 index 0000000..0b1e9f8 --- /dev/null +++ b/src/problem_0896_monotonic_array/mod.rs @@ -0,0 +1,24 @@ +pub mod iterative; + +pub trait Solution { + fn is_monotonic(nums: Vec) -> bool; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + (&[1, 2, 2, 3] as &[_], true), + (&[6, 5, 4, 4], true), + (&[1, 3, 2], false), + (&[5, 3, 2, 4, 1], false), + (&[1, 1, 1], true), + ]; + + for (nums, expected) in test_cases { + assert_eq!(S::is_monotonic(nums.to_vec()), expected); + } + } +}