739. Daily Temperatures

2018/11/26 20:54

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].

Solution

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
}

0
0 收藏

作者的其它热门文章 0 评论
0 收藏
0   