Leetcode-Daily Temperatures

problem

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].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

Analysis

这道题考的是stack的思想。但是我这里是用数组来模拟stack的,方法大同小异。首先就是使用stack或者queue最关键的一点就是要先推入一个-1,或者每次都用size()这个函数来判断。然后这道题的关键在于,要把当前的访问到的temperature与栈中的元素比较,如果比栈顶的元素大的话就把栈顶的元素pop出来,然后,这里用当前元素在温度这个数组里的index减去栈顶元素的值就是等的天数。然后继续对新的栈顶元素进行比较,直至栈顶元素不满足比当前元素小或者栈已经为空了(vector中只剩下-1)。最后把当前的元素推入栈。当整个temperature数组都遍历完了,对栈中剩下元素的等待天数全部赋值为0。

Code

complexity

时间复杂度: O(n)
空间复杂度: O(n)

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        std::vector<int> record;
        if (temperatures.size() == 0) return record;
        for (int i = 0; i < temperatures.size(); i++) {
            record.push_back(0);
        }
        vector<int> tep;
        if (temperatures.size() == 1) return record;
        tep.push_back(-1);

        for (int i = 0; i < temperatures.size(); i++) {
            while (tep.back() != -1 && temperatures[i] > temperatures[tep.back()]) {
                record[tep.back()] = i - tep.back();
                tep.pop_back();
            }
            tep.push_back(i);
        }
        for (int i = 0; i < tep.size(); i++) 
            record[tep[i]] = 0;

        return record;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值