From 2b28e58463fbb679d6952d1b70f783251d6dd1d5 Mon Sep 17 00:00:00 2001 From: wuhesheng Date: Sun, 28 Apr 2024 14:11:51 +0800 Subject: [PATCH] Add problem 0739: Daily Temperatures --- src/lib.rs | 1 + src/problem_0739_daily_temperatures/dp.rs | 38 ++++++++++++++++++++++ src/problem_0739_daily_temperatures/mod.rs | 21 ++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 src/problem_0739_daily_temperatures/dp.rs create mode 100644 src/problem_0739_daily_temperatures/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 3f2d6ab..f3c2370 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -345,6 +345,7 @@ pub mod problem_0677_map_sum_pairs; pub mod problem_0717_1_bit_and_2_bit_characters; pub mod problem_0720_longest_word_in_dictionary; pub mod problem_0738_monotone_increasing_digits; +pub mod problem_0739_daily_temperatures; pub mod problem_0779_k_th_symbol_in_grammar; pub mod problem_0784_letter_case_permutation; pub mod problem_0791_custom_sort_string; diff --git a/src/problem_0739_daily_temperatures/dp.rs b/src/problem_0739_daily_temperatures/dp.rs new file mode 100644 index 0000000..6625612 --- /dev/null +++ b/src/problem_0739_daily_temperatures/dp.rs @@ -0,0 +1,38 @@ +pub struct Solution; + +impl Solution { + pub fn daily_temperatures(temperatures: Vec) -> Vec { + let mut result = vec![0; temperatures.len()]; + 'loop1: for idx in (0..temperatures.len() - 1).rev() { + if temperatures[idx] < temperatures[idx + 1] { + result[idx] = 1; + } else { + let mut offset = result[idx + 1] as usize + 1; + while temperatures[idx + offset] <= temperatures[idx] { + if result[idx + offset] == 0 { + result[idx] = 0; + continue 'loop1; + } + offset += result[idx + offset] as usize; + } + result[idx] = offset as i32; + } + } + + result + } +} + +impl super::Solution for Solution { + fn daily_temperatures(t: Vec) -> Vec { + Self::daily_temperatures(t) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_0739_daily_temperatures/mod.rs b/src/problem_0739_daily_temperatures/mod.rs new file mode 100644 index 0000000..99fe3fd --- /dev/null +++ b/src/problem_0739_daily_temperatures/mod.rs @@ -0,0 +1,21 @@ +pub mod dp; + +pub trait Solution { + fn daily_temperatures(t: Vec) -> Vec; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [( + &[73, 74, 75, 71, 69, 72, 76, 73] as &[_], + &[1, 1, 4, 2, 1, 1, 0, 0] as &[_], + )]; + + for (t, expected) in test_cases { + assert_eq!(S::daily_temperatures(t.to_vec()), expected); + } + } +}