Daily Temperatures With Monotonic Stack
Solve daily-wait-until-warmer with a monotonic stack of unresolved indexes, settling each in O(1) amortized instead of scanning forward from every day.
Code
package main
import "fmt"
// dailyTemperatures 返回每天还要等几天才更暖:单调栈保存未决的下标
func dailyTemperatures(temps []int) []int {
wait := make([]int, len(temps))
stack := make([]int, 0, len(temps))
for i, t := range temps {
// 栈内下标的温度沿栈单调不增;当前更暖就逐个弹出结算
for len(stack) > 0 && temps[stack[len(stack)-1]] < t {
top := stack[len(stack)-1]
stack = stack[:len(stack)-1]
wait[top] = i - top
}
stack = append(stack, i)
}
return wait
}
func main() {
fmt.Println(dailyTemperatures([]int{73, 74, 75, 71, 69, 72, 76, 73}))
fmt.Println(dailyTemperatures([]int{30, 30, 31}))
fmt.Println(dailyTemperatures([]int{40, 39, 38}))
}Runtime behavior
Everything happens inside the functions dailyTemperatures and main.
The loop for i, t := range temps is the only repeated construct.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
The signature doing the work here: func dailyTemperatures(temps []int) []int
Running the file executes main, which drives dailyTemperatures in order.
Key statements
for i, t := range temps {
// 栈内下标的温度沿栈单调不增;当前更暖就逐个弹出结算
for len(stack) > 0 && temps[stack[len(stack)-1]] < t {
top := stack[len(stack)-1]
stack = stack[:len(stack)-1]
wait[top] = i - top
}
stack = append(stack, i)
}
func main() {
fmt.Println(dailyTemperatures([]int{73, 74, 75, 71, 69, 72, 76, 73}))
fmt.Println(dailyTemperatures([]int{30, 30, 31}))
fmt.Println(dailyTemperatures([]int{40, 39, 38}))
}
stack := make([]int, 0, len(temps))
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.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.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 Daily Temperatures With Monotonic Stack?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.