Skip to content

Commit

Permalink
Add problem 0739: Daily Temperatures
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed Apr 28, 2024
1 parent 2decde6 commit d8043ed
Show file tree
Hide file tree
Showing 3 changed files with 60 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 @@ -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;
Expand Down
38 changes: 38 additions & 0 deletions src/problem_0739_daily_temperatures/dp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
pub struct Solution;

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

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
21 changes: 21 additions & 0 deletions src/problem_0739_daily_temperatures/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
pub mod dp;

pub trait Solution {
fn daily_temperatures(t: Vec<i32>) -> Vec<i32>;
}

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

pub fn run<S: Solution>() {
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);
}
}
}

0 comments on commit d8043ed

Please sign in to comment.