[leetcode]739. Daily Temperatures

[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.csdn.net/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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值