class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
}
};
剑指 Offer II 038. 每日温度
请根据每日 气温
列表 temperatures
,重新生成一个列表,要求其对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0
来代替。
示例 1:
输入: temperatures
= [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]
示例 2:
输入: temperatures = [30,40,50,60] 输出: [1,1,1,0]
示例 3:
输入: temperatures = [30,60,90] 输出: [1,1,0]
提示:
1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100
注意:本题与主站 739 题相同: https://leetcode.cn/problems/daily-temperatures/
原站题解
python3 解法, 执行用时: 196 ms, 内存消耗: 21.8 MB, 提交时间: 2022-11-12 12:37:28
class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: length = len(temperatures) ans = [0] * length stack = [] for i in range(length): temperature = temperatures[i] while stack and temperature > temperatures[stack[-1]]: prev_index = stack.pop() ans[prev_index] = i - prev_index stack.append(i) return ans
python3 解法, 执行用时: 2088 ms, 内存消耗: 21.6 MB, 提交时间: 2022-11-12 12:35:00
class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: n = len(temperatures) ans, nxt, big = [0] * n, dict(), 10**9 for i in range(n - 1, -1, -1): warmer_index = min(nxt.get(t, big) for t in range(temperatures[i] + 1, 102)) if warmer_index != big: ans[i] = warmer_index - i nxt[temperatures[i]] = i return ans