每日温度
- 理解为什么用栈:一种在连续数据里的局部关系,这道题体现在temp[0]只和第一个比它大的值下标有关
- 题解1 逆波兰栈
- 改进(单调栈)
 
 
给定一个整数数组
temperatures ,表示每天的温度,返回一个数组 
answer ,其中 
answer[i] 是指对于第 
i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 
0 来代替。 
 
示例 1:
 输入: temperatures = [73,74,75,71,69,72,76,73]
 输出: [1,1,4,2,1,1,0,0]
示例 2:
 输入: temperatures = [30,40,50,60]
 输出: [1,1,1,0]
示例 3:
 输入: temperatures = [30,60,90]
 输出: [1,1,0]
提示:
- 1 <= temperatures.length<= 1 0 5 10^5 105
- 30 <= temperatures[i]<= 100
理解为什么用栈:一种在连续数据里的局部关系,这道题体现在temp[0]只和第一个比它大的值下标有关
题解1 逆波兰栈
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        vector<int> ret(temperatures.size(), 0);
        stack<int> num_stk;
        stack<int> tem_stk;
        for(int i = 0; i < temperatures.size(); i++){
            if(tem_stk.empty()){
                tem_stk.push(temperatures[i]);
                num_stk.push(i);
            }
            else{
                while (tem_stk.size() && temperatures[i] > tem_stk.top()){
                    ret[num_stk.top()] = i-num_stk.top();
                    tem_stk.pop();
                    num_stk.pop();
                }
                tem_stk.push(temperatures[i]);
                num_stk.push(i); 
            }
            
        }
        return ret;
    }
};

改进(单调栈)
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        vector<int> ret(temperatures.size(), 0);
        // 放下标
        stack<int> idx_stk;
        for(int i = temperatures.size()-1; i >= 0; i--){
            while(idx_stk.size() && temperatures[idx_stk.top()] <= temperatures[i])
                idx_stk.pop();
            ret[i] = idx_stk.empty() ? 0 : idx_stk.top()-i;
            idx_stk.push(i);
        }
        return ret;
    }
};




















