题干:
代码:
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
stack<int>st;
vector<int>res(temperatures.size());
st.push(0);
for(int i = 1; i < temperatures.size(); i++){
if(temperatures[i] <= temperatures[st.top()]) st.push(i);
else{
while(!st.empty() && temperatures[i] > temperatures[st.top()]){
res[st.top()] = i - st.top();
st.pop();
}
st.push(i);
}
}
return res;
}
};
单调栈:通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,此时我们就要想到可以用单调栈了。
这里我们要使用递增循序(再强调一下是指从栈头到栈底的顺序),因为只有递增的时候,栈里要加入一个元素i的时候,才知道栈顶元素在数组中右面第一个比栈顶元素大的元素是i。
即:如果求一个元素右边第一个更大元素,单调栈就是递增的,如果求一个元素右边第一个更小元素,单调栈就是递减的。