探索队列和栈 每日温度

根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。
例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。

代码如下:

```cpp
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& T) {
        int n=T.size();
        vector<int> day(n,0);
        stack<int> s;
        int nums;
        for(int i=0;i<T.size();i++){
            while(!s.empty() && T[i]>T[s.top()]){//当s不为空并且i天温度高于栈顶的天数时
                int t=s.top();//t是栈顶的天数
                s.pop();//栈顶出栈
                day[t]=i-t;//第i天温度高于第t天
            }
            s.push(i);//将第i天入栈
        }
        return day;
    }
};
```

发布了70 篇原创文章 · 获赞 39 · 访问量 2270

猜你喜欢

转载自blog.csdn.net/weixin_45221477/article/details/105008334