Stack of applications: daily temperature

Subject description:

According to the list of daily temperatures, rebuild a list, enter the corresponding position is how long you need to wait until the temperature rises more than the number of days of that date. After all, if not increased, please use 0 instead of at the location.

For example, given a list of temperatures = [73, 74, 75, 71, 69, 72, 76, 73]your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Tip: temperature range length of the list is [1, 30000]. Value for each temperature are degrees Fahrenheit, are [30, 100]integers in the range.

Topic Analysis:

The input 73, it takes after a day in order to wait until the temperature rise, that is, when the next day, the temperature was raised to 74, the corresponding result is 1.

For input 74, it needs after a day in order to wait until the temperature rises, that is, when the third day, the temperature was raised to 75, the corresponding result is 1.

The input 75, it is found that the temperature after 1 day 71, does not exceed it, continue to wait until other four days , until the seventh genius elevated temperature, the temperature was raised to 76, the corresponding result is 4.

The input 71, it is found that the temperature after 1 day 69, does not exceed it, continues the like, has waited two days , until the sixth genius temperature, the temperature was raised to 72, the corresponding result is 2.

The input 69, which after a day after the temperature is found 72, it has been exceeded, the corresponding result is 1.

The input 72, which after a day after the temperature is found 76, it has been exceeded, the corresponding result is 1.

The input 76, the follow-up no temperature may exceed it, the corresponding result is 0.

The input 73, the follow-up no temperature may exceed it, the corresponding result is 0.

Specific code as follows:

t = [73, 74, 75, 71, 69, 72, 76, 73]

def daily_temp(tem):
    # 模拟一个递减栈,存放当天的索引
    stack = []
    # 结果列表,几天后气温才升高
    res = [0] * len(tem)
    # 循环整个列表
    for i in range(len(tem)):
        # 当栈不为空且当前天数的气温大于栈顶的气温时,计算栈顶那天过几天气温才会升高
        while stack and tem[i] > tem[stack[-1]]:
            res[stack[-1]] = i - stack[-1]
            # 计算完出栈
            stack.pop()
        # 栈为空或者没有超过的温度,入栈一个
        stack.append(i)

    return res

if __name__ == '__main__':
    print(daily_temp(t))

Guess you like

Origin www.cnblogs.com/milesma/p/12461949.html