Leetcode739. 每日温度

文章介绍了LeetCode题目739每日温度问题的两种解法,使用单调栈分别从左到右和从右到左遍历数组,分析了每种方法的时间复杂度为O(n),空间复杂度分别为O(n)和O(min(n,U)),其中U是温度范围。
摘要由CSDN通过智能技术生成

Every day a Leetcode

题目来源:739. 每日温度

解法1:单调栈-从左到右

单调栈中记录还没算出「下一个更大元素」的那些数(的下标)。

代码:

/*
 * @lc app=leetcode.cn id=739 lang=cpp
 *
 * [739] 每日温度
 */

// @lc code=start

// 暴力
// Time Limit Exceeded

// class Solution
// {
// public:
//     vector<int> dailyTemperatures(vector<int> &temperatures)
//     {
//         int n = temperatures.size();
//         vector<int> answer(n, 0);
//         for (int i = 0; i < n - 1; i++)
//         {
//             int j = i + 1;
//             while (j < n && temperatures[i] >= temperatures[j])
//                 j++;
//             answer[i] = j == n ? 0 : j - i;
//         }
//         return answer;
//     }
// };

// 单调栈

class Solution
{
public:
    vector<int> dailyTemperatures(vector<int> &temperatures)
    {
        int n = temperatures.size();
        vector<int> answer(n, 0);
        stack<int> indices;
        for (int i = 0; i < n; i++)
        {
            while (!indices.empty())
            {
                int preIndex = indices.top();
                // 如果当前温度<=之前的温度,退出
                if (temperatures[i] <= temperatures[preIndex])
                    break;
                // 否则,之前温度对应下标的天数=当前下标i-之前下标preIndex
                indices.pop();
                answer[preIndex] = i - preIndex;
            }
            indices.push(i);
        }
        return answer;
    }
};
// @lc code=end

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(n),其中 n 为数组 temperatures 的长度。

空间复杂度:O(n),其中 n 为数组 temperatures 的长度。注意这种写法栈中可以有重复元素。

解法2:单调栈-从右到左

单调栈中记录下一个更大元素的「候选项」。

代码:

// 单调栈-从右到左

class Solution
{
public:
    vector<int> dailyTemperatures(vector<int> &temperatures)
    {
        int n = temperatures.size();
        vector<int> ans(n);
        stack<int> st;
        for (int i = n - 1; i >= 0; i--)
        {
            int t = temperatures[i];
            // 当前温度大于等于之前的最大温度,小于等于当前温度的栈中温度全部全掉
            while (!st.empty() && t >= temperatures[st.top()])
                st.pop();
            if (!st.empty())
                ans[i] = st.top() - i;
            st.push(i);
        }
        return ans;
    }
};

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(n),其中 n 为数组 temperatures 的长度。

空间复杂度:O(min(n,U)),其中 U=max⁡(temperatures)−min⁡(temperatures)+1。返回值不计入,仅考虑栈的最大空间消耗。

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值