Skip to content

Commit

Permalink
Solve leetcode 739
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielseibel1 committed Oct 6, 2023
1 parent da59f04 commit 7e62199
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/lc739.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
pub fn daily_temperatures(temperatures: Vec<i32>) -> Vec<i32> {
let mut ans = std::iter::repeat(0).take(temperatures.len()).collect::<Vec<i32>>();
let mut stk = Vec::<usize>::with_capacity(temperatures.len());
for i in 0..temperatures.len() {
while let Some(pos) = stk.last() {
if temperatures[*pos as usize] < temperatures[i] {
let p = stk.pop().unwrap();
ans[p] = (i - p) as i32;
} else {
break;
}
}
stk.push(i);
}
while let Some(pos) = stk.pop() {
ans[pos] = 0;
}
ans
}

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

#[test]
fn test_daily_temperatures() {
let result = daily_temperatures(vec![73, 74, 75, 71, 69, 72, 76, 73]);
assert_eq!(result, vec![1, 1, 4, 2, 1, 1, 0, 0]);
let result = daily_temperatures(vec![30, 40, 50, 60]);
assert_eq!(result, vec![1, 1, 1, 0]);
let result = daily_temperatures(vec![30, 60, 90]);
assert_eq!(result, vec![1, 1, 0]);
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ pub mod lc74;
pub mod lc143;
pub mod lc206;
pub mod lc22;
pub mod lc739;

0 comments on commit 7e62199

Please sign in to comment.