Problem
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ᵗʰ
day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0
instead.
https://leetcode.com/problems/daily-temperatures/
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 <= 10⁵
30 <= temperatures[i] <= 100
Test Cases
1 | class Solution: |
1 | import pytest |
Thoughts
跟 496. Next Greater Element I 和 503. Next Greater Element II 类似,本质都是求当前元素右侧第一个比当前元素大的数,利用单调栈求解。本题是要计算找到的 next greater 温度的下标,与当前温度下标的差值。为了方便得到 next greater 的下标,直接把下标入栈。
Code
Backward Iteration
1 | class Solution: |
Forward Iteration
1 | class Solution: |
这里用正向循环就可以做 in-place 修改。