题目描述
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 i^th
day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0
instead.
Example 1:
1 | Input: temperatures = [73,74,75,71,69,72,76,73] |
Example 2:
1 | Input: temperatures = [30,40,50,60] |
Example 3:
1 | Input: temperatures = [30,60,90] |
Constraints:
1 <= temperatures.length <= 10^5
30 <= temperatures[i] <= 100
解题方法
单调栈
题目的意思实际上就是给定一个数组,每个位置上有整数值。对于每个位置,在该位置右侧找到第一个比当前元素更大的元素。求「该元素」与「右侧第一个比当前元素更大的元素」之间的距离,将所有距离保存为数组返回结果。
最简单的思路是对于每个温度值,向后依次进行搜索,找到比当前温度更高的值。
更好的方式使用「单调递增栈」,栈中保存元素的下标。
解题思路:
- 将答案数组
ans
全部赋值为0
,然后遍历数组每个位置元素。 - 如果栈为空,则将当前元素的下标入栈。
- 如果栈不为空,且当前数字大于栈顶元素对应的数字,栈顶元素出栈,计算下标差。
- 此时当前元素就是栈顶元素的下一个更高值,将其下标差存入
ans
数组中保存起来,判断栈顶元素。 - 直到当前数字小于或等于栈顶元素,则停止出栈,将当前元素下标入栈。
- 输出数组
ans
1 | class Solution: |
时间复杂度:$O(n)$
空间复杂度:$O(n)$