739. Daily Temperatures

原创
2018/11/26 20:54
阅读数 96

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

从后向前,将大值压入栈中,在压栈过程中,将小值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
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
在线直播报名
返回顶部
顶部