739. Daily Temperatures

Description

Tag:Stack, Hash Table
Difficulty: Mediumthis

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

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

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].element

Solution

從後向前,將大值壓入棧中,在壓棧過程當中,將小值pop出去,而後依次查找便可。input

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
}
相關文章
相關標籤/搜索