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
Companies:
Amazon, Facebook, Apple, Zillow, Google, Bloomberg, Adobe, Microsoft, Uber, DE Shaw
Related Topics:
Array, Stack, Monotonic Stack
Similar Questions:
Scan from right to left, use a stack s
to track the index of large numbers.
For A[i]
, keep popping s
if A[s.top()] <= A[i]
. Then the answer for A[i]
is s.top() - i
if s
is not empty; otherwise 0
. Push i
into the stack and repeat the process.
// OJ: https://leetcode.com/problems/daily-temperatures/
// Author: github.com/lzl124631x
// Time: O(T)
// Space: O(T)
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& A) {
stack<int> s;
vector<int> ans(A.size());
for (int i = A.size() - 1; i >= 0; --i) {
while (s.size() && A[s.top()] <= A[i]) s.pop();
ans[i] = s.size() ? s.top() - i : 0;
s.push(i);
}
return ans;
}
};
Same idea as in 496. Next Greater Element I (Easy).
// OJ: https://leetcode.com/problems/daily-temperatures/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& A) {
vector<int> ans(A.size());
stack<int> s;
for (int i = 0; i < A.size(); ++i) {
while (s.size() && A[s.top()] < A[i]) {
ans[s.top()] = i - s.top();
s.pop();
}
s.push(i);
}
return ans;
}
};