Leetcode_739. 每日温度(单调栈)

对每一个位置,求右边第一个比它大的数的位置。从后往前扫一遍,维护单调栈。

code

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& T) {
        int n=T.size();
        vector<int> ans(n,0);
        stack<int> s;
        for(int i=n-1;i>=0;i--){
            while(s.size()>0 && T[s.top()]<=T[i]){
                s.pop();
            }
            if(s.empty()){
                ans[i]=0;
            }else{
                ans[i]=s.top()-i;
            }
            s.push(i);
        }
        return ans;
    }
};
posted @ 2020-03-25 14:28  Keane1998  阅读(123)  评论(0编辑  收藏  举报