题目描述
Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
样例
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
算法1
(单调栈) $O(n)$
利用递减单调栈找到右边大于栈顶的元素,弹出栈顶直到满足单调递减,同时记录弹出元素与当前i的距离,保存在res数组中即是答案。
时间复杂度
遍历一次 O(n)
需要栈存储,O(n)
参考文献
C++ 代码
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T) {
stack<int> st;
int n=T.size();
vector<int> res(n);
for(int i=0; i<n; i++)
{
while(!st.empty() && T[st.top()]<T[i])
{
res[st.top()]=i-st.top();
st.pop();
}
st.push(i);
}
return res;
}
};