Given an array of integers temperatures
represents the daily temperatures, return an array answer
such that answer[i]
is the number of days you have to wait after the ith
day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0
instead.
Example 1:
Input: temperatures = [73,74,75,71,69,72,76,73] Output: [1,1,4,2,1,1,0,0]
Example 2:
Input: temperatures = [30,40,50,60] Output: [1,1,1,0]
Example 3:
Input: temperatures = [30,60,90] Output: [1,1,0]
Constraints:
1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100
题目大意是给定一个数组,里面的数值表示每天的气温,对于数组中的每一天要求算出当前天之后需要等待多少天才能等到气温比当前天高的那一天,要是数组中不存在这样的一天答案为0天。
这道题其实就是求下一个更大数(Next Greater Number),只是被包装成气温相关的问法。换种问法就是,给定一个数组,对于数组中每个数,要求找出当前数(索引为i)的下一个更大数(索引为j)与当前数的距离(j - i),如不存在下个更大数那么距离为0。解法跟496. Next Greater Element I和503. Next Greater Element II一样,都是用单调递减栈。
定义一个堆栈要始终维持栈是单调递减的,遍历数组temperature,当栈为空或者当前数比栈顶的数小时,就把当前数值压入栈(注:由于答案要求距离,所以压入栈的是当前数的索引值);当遇到当前数比栈顶的数大时,就把栈中从栈顶开始所有比当前数小的数都弹出栈,当前数就是所有被弹出栈的数的下一个更大数,计算二者在数组中的距离存入答案,最后把当前数压入栈。遍历完这个数组后,栈里面剩下的数都不存在下一个更大数。
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n = len(temperatures)
res = [0] * n
st = []
for i in range(n):
while st and temperatures[st[-1]] < temperatures[i]:
j = st.pop()
res[j] = i - j
st.append(i)
return res