739. 每日温度

题目

暴力

暴力有两种:

  1. 一种是每次遍历当前位置后续的元素,寻找更大值,由于数组长度最大为 1e5 ,因此会超时;
  2. 第二种是建立一个元素索引,每次遍历当前元素温度 +1 到 100 度的元素,若能找到,则为目标,若找不到,说明结果为 0 。
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int n = temperatures.size();
        vector<int> ans(n), next(101, INT_MAX);
        for(int i = n - 1; i >= 0; --i) {
            int index = INT_MAX;
            for(int j = temperatures[i] + 1; j <= 100; ++j)
                index = min(index, next[j]);
            if(index != INT_MAX)
                ans[i] = index - i;
            next[temperatures[i]] = i;
        }
        return ans;
    }
};

单调栈

维护一个栈,将数组元素按顺序入栈,每个元素入栈的时候判断一下该元素是否比之前某些元素大,如果是,则更新栈内相关元素,如果不是,则入栈。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BeZer0

打赏一杯奶茶支持一下作者吧~~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值