[leetcode]739. Daily Temperatures

博客围绕LeetCode 739题每日温度展开。题目要求根据每日温度列表,计算出等待更暖和天气的天数。博主先用暴力法求解超时,后参考大神解法。还介绍了两种实现方法,一是暴力法,时间复杂度O(n*n),二是复杂度为O(n)的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[leetcode]739. Daily Temperatures


Analysis

跟爸妈一起旅游了一个礼拜,然后就回学校准备开学啦~—— [心塞,这么大了还是很讨厌开学]

Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
一开始用暴力解决,然后提交果然超时了,然后参考了一下大神们的解法~具体可以参考一下:https://blog.youkuaiyun.com/kakitgogogo/article/details/78794032

Implement

方法一(暴力,O(n*n))

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int len = temperatures.size();
        vector<int> res;
        for(int i=0; i<len; i++){
            int cur = temperatures[i];
            int cnt = 0;
            bool flag = false;
            for(int j=i+1; j<len; j++){
                if(temperatures[j] > cur){
                    cnt++;
                    flag = true;
                    break;
                }
                cnt++;
            }
            if(flag)
                res.push_back(cnt);
            else
                res.push_back(0);
        }
        return res;
    }
};

方法二(O(n))

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值