Daily Temperatures
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, put0instead.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
temperatureswill be in the range[1, 30000]. Each temperature will be an integer in the range[30, 100].
解题思路
法一:从后往前遍历 T,对于当前温度 t 及其索引 i,取温度 t+1~100 中的最小索引 j,在温度 t 的那一天 i 需等待 j-i 天。最后更新 t 的索引为 i。
法二:要找比当天温度高的下一天,考虑用递减栈,栈内温度递减。以 i 遍历数组,若栈不为空且当前温度大于栈顶温度 t,必须出栈以保持递减性,此时在温度 t 的那一天 j 需等待 i-j 天。否则,当前温度的索引入栈,等待温度高的那一天到来。
复杂度分析
- 时间复杂度:法一 $O(wn)$,
w为温度种数;法二 $O(n)$,每个元素最多进栈出栈各一次。 - 空间复杂度:法一 $O(n+w)$,保存结果和温度索引;法二栈中最多需要保存
n个元素。
代码
1 | class Solution_1 { |