Description
Tag:Stack, Hash Table Difficulty: Medium
Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
从后向前,将大值压入栈中,在压栈过程中,将小值pop出去,然后依次查找即可。
type ele struct {
index int
temperature int
}
var stack []ele
var top = -1
func dailyTemperatures(T []int) []int {
size := len(T)
stack = make([]ele, size)
result := make([]int, size)
for i:= size -1; i>=0;i-- {
result[i] = find(T[i], i)
push(T[i], i)
}
return result
}
func find(t int, index int) int {
for i:=top; i>=0; i-- {
if stack[i].temperature > t {
return stack[i].index - index
}
}
return 0
}
func push(t int, i int) {
for top >=0 && stack[top].temperature <= t {
top--
}
top++
element := ele{i, t}
stack[top] = element
}