Warmer Days Wait On A Monotonic Stack
Keep unresolved indexes on a stack whose temperatures never increase, popping to settle wait distances the moment a warmer day appears.
Code
// 栈里保存还没等到更暖天的下标:温度沿栈单调不增
fn daily_temperatures(temps: &[i32]) -> Vec<usize> {
let mut wait = vec![0usize; temps.len()];
let mut stack: Vec<usize> = Vec::with_capacity(temps.len());
for (i, &t) in temps.iter().enumerate() {
// 当前更暖就结算栈顶:wait 等于下标差
while let Some(&top) = stack.last() {
if temps[top] >= t {
break;
}
stack.pop();
wait[top] = i - top;
}
stack.push(i);
}
wait
}
fn main() {
let answer = daily_temperatures(&[73, 74, 75, 71, 69, 72, 76, 73]);
println!("{answer:?}");
let flat = daily_temperatures(&[30, 30, 31]);
println!("{flat:?}");
let cooling = daily_temperatures(&[40, 39, 38]);
println!("{cooling:?}");
}How it works
The moving parts sit in the functions daily_temperatures and main.
Iteration happens inside for (i, &t) in temps.iter().enumerate() — everything outside it runs once.
What to watch for
- Imports, where present, target standard-library modules only.
Putting it to use
Entry signature: fn daily_temperatures(temps: &[i32]) -> Vec<usize>
main sequences daily_temperatures; executing the file runs that flow once.
Core lines
while let Some(&top) = stack.last() {
if temps[top] >= t {
break;
}
stack.pop();
wait[top] = i - top;
}
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Warmer Days Wait On A Monotonic Stack?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.