Leecode每日温度

每日温度

问题描述:

请根据每日 气温 列表 temperatures
,重新生成一个列表,要求其对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。

思路:

两个for循环,检测到后面第一个大于当日温度的天数输出
最差时间复杂度:O(n²)

结果:超时
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        vector<int> a;
        for(int i=0;i<temperatures.size();i++)
        {
            int j;
            for(j=i;j<temperatures.size();j++)
            {
                if(temperatures[j]>temperatures[i]){
                a.push_back(j-i);
                break;
                }                
            }
            if(j==temperatures.size())
            a.push_back(0);
        }
        return a;
    }
};

扒拉扒拉:

单调递减栈:从栈底到栈顶依次递减
因为题目只需单向遍历,找出第一个非递减位置。
理解:向右遍历,找出第一个非递减位置,非递减位置之前小于当前元素的进栈,其他留在栈中等待,同时记录进栈元素与非递减位置的距离。
用到操作:
stack.top()获取栈顶元素;
stack.pop()出栈;
stack.push(i)进栈;

解:

一个for循环,当元素单调递减时,元素进栈,当for循环遍历到的位置数值大于栈顶所在的数值时,储存栈顶元素位置到当前遍历元素位置差值,也就是最小等待天数
时间复杂度:O(n)。
结果:pass

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        vector<int> a(temperatures.size());
        stack<int> stk_temperature;
        for(int i=0;i<temperatures.size();i++)
        {
            while(!stk_temperature.empty()&&temperatures[i]>temperatures[stk_temperature.top()])
            {
                a[stk_temperature.top()]=i-stk_temperature.top();
                stk_temperature.pop();
            }
            stk_temperature.push(i);
        }
        return a;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值