LeetCode 739. 每日温度

leetcode acwing

单调栈 \(O(n)\)

维护一个严格单调递减的单调栈,对于单调栈的栈顶元素来说,待加入的元素假如比它大,那么对于它就是最近的比它大的元素。不要光从待加入元素作为考虑问题的主体。栈顶元素也是一个考虑角度。另外,单调栈一般是存放下标。

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& T) {
        vector<int> res(T.size());
        stack<int> st;

        for (int i = 0; i < T.size(); i ++)
        {
            while(!st.empty() && T[i] > T[st.top()])
            {
                res[st.top()] = i - st.top();
                st.pop();
            }
            st.push(i);
        }

        return res;
    }
};
posted @ 2021-01-07 14:02  alexemey  阅读(37)  评论(0)    收藏  举报