Skip to content

739. Daily Temperatures

难度: Medium

刷题内容

原题连接

  • https://leetcode-cn.com/problems/daily-temperatures/

内容描述

``` 根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高的天数。如果之后都不会升高,请输入 0 来代替。

例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。

提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的都是 [30, 100] 范围内的整数。 ```

解题方案

思路 1

暴力超时。
采用递减栈思维,用栈存下表
当前值小于栈顶值,入栈
否则出站,出栈index的结果为当前处理下表和出栈下标的差值。
vector<int> dailyTemperatures(vector<int>& temperatures) {
    if(temperatures.size()==0)
        return temperatures;
    vector<int> ans(temperatures.size(), 0);
    stack<int> index;
    for(int i=0;i<temperatures.size();i++){

        while(!index.empty() && temperatures[i]>temperatures[index.top()]){
            int tmp = index.top();
            index.pop();
            ans[tmp]=i-tmp;
        }
        index.push(i);  
    }
    return ans;
}

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组