Skip to content

Commit

Permalink
Add problem 1944: Number of Visible People in a Queue
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 29, 2023
1 parent abb2aec commit 029d6cc
Show file tree
Hide file tree
Showing 3 changed files with 67 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 @@ -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;
Expand Down
21 changes: 21 additions & 0 deletions src/problem_1944_number_of_visible_people_in_a_queue/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
pub mod stack;

pub trait Solution {
fn can_see_persons_count(heights: Vec<i32>) -> Vec<i32>;
}

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

pub fn run<S: Solution>() {
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);
}
}
}
45 changes: 45 additions & 0 deletions src/problem_1944_number_of_visible_people_in_a_queue/stack.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
pub struct Solution;

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

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

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}

0 comments on commit 029d6cc

Please sign in to comment.