From 029d6cc0371f138c6b0b28ca0c82b1a10a74b20f Mon Sep 17 00:00:00 2001 From: EFanZh Date: Wed, 29 Nov 2023 23:34:44 +0800 Subject: [PATCH] Add problem 1944: Number of Visible People in a Queue --- src/lib.rs | 1 + .../mod.rs | 21 +++++++++ .../stack.rs | 45 +++++++++++++++++++ 3 files changed, 67 insertions(+) create mode 100644 src/problem_1944_number_of_visible_people_in_a_queue/mod.rs create mode 100644 src/problem_1944_number_of_visible_people_in_a_queue/stack.rs diff --git a/src/lib.rs b/src/lib.rs index 75402ce6..9826b185 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1360,6 +1360,7 @@ pub mod problem_1929_concatenation_of_array; pub mod problem_1935_maximum_number_of_words_you_can_type; pub mod problem_1936_add_minimum_number_of_rungs; pub mod problem_1941_check_if_all_characters_have_equal_number_of_occurrences; +pub mod problem_1944_number_of_visible_people_in_a_queue; pub mod problem_1945_sum_of_digits_of_string_after_convert; pub mod problem_1952_three_divisors; pub mod problem_1957_delete_characters_to_make_fancy_string; diff --git a/src/problem_1944_number_of_visible_people_in_a_queue/mod.rs b/src/problem_1944_number_of_visible_people_in_a_queue/mod.rs new file mode 100644 index 00000000..93be5267 --- /dev/null +++ b/src/problem_1944_number_of_visible_people_in_a_queue/mod.rs @@ -0,0 +1,21 @@ +pub mod stack; + +pub trait Solution { + fn can_see_persons_count(heights: Vec) -> Vec; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + (&[10, 6, 8, 5, 11, 9] as &[_], &[3, 1, 2, 1, 1, 0] as &[_]), + (&[5, 1, 2, 3, 10], &[4, 1, 1, 1, 0]), + ]; + + for (heights, expected) in test_cases { + assert_eq!(S::can_see_persons_count(heights.to_vec()), expected); + } + } +} diff --git a/src/problem_1944_number_of_visible_people_in_a_queue/stack.rs b/src/problem_1944_number_of_visible_people_in_a_queue/stack.rs new file mode 100644 index 00000000..f7c1a306 --- /dev/null +++ b/src/problem_1944_number_of_visible_people_in_a_queue/stack.rs @@ -0,0 +1,45 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn can_see_persons_count(heights: Vec) -> Vec { + let mut stack = Vec::new(); + let mut heights = heights; + + for target in heights.iter_mut().rev() { + let mut count = 0; + + while let Some(&top) = stack.last() { + count += 1; + + if top < *target { + stack.pop(); + } else { + break; + } + } + + stack.push(*target); + *target = count; + } + + heights + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn can_see_persons_count(heights: Vec) -> Vec { + Self::can_see_persons_count(heights) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +}