1、单调栈
我们可以利用一个单调递减的单调栈来处理每一天的问题。我们遍历每一天的温度:1、当栈为空时,我们将当日温度压入栈中;2、当栈不为空时,我们比较栈顶元素和当日温度。当当日温度大于栈顶元素对应的温度时,我们将栈顶元素 p r e v I n d e x prevIndex prevIndex出栈并更新对应天数为 i − p r e v I n d e x i - prevIndex i−prevIndex,循环直至栈顶元素对应天数的温度大于当日温度或栈为空。最后我们将新一天的温度压入栈中。
class Solution {
public:
vector<int> dailyTemperatures(vector<int> &temperatures) {
vector<int> result(temperatures.size(), 0);
stack<int> st;
for (int i = 0; i < temperatures.size(); ++i) {
if (st.empty()) st.push(i);
else {
if (temperatures[st.top()] < temperatures[i]) {
while (!st.empty() && temperatures[st.top()] < temperatures[i]) {
int prevIndex = st.top();
result[prevIndex] = i - prevIndex;
st.pop();
}
}
st.push(i);
}
}
return result;
}
};