Daily Temperatures

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

Given a list of daily temperatures T, return a list such 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 of temperatures T = [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].

给定每日温度列表T,返回一个列表,使得对于输入中的每一天,您可以告诉您需要等待多少天才能达到更温暖的温度。 如果没有可能的未来日期,请改为0。

例如,给定温度列表T = [73,74,75,71,69,72,76,73],您的输出应为[1,1,4,2,1,1,0,0]。

注意:温度的长度将在[1,30000]范围内。 每个温度将是[30,100]范围内的整数。

2,题目思路

对于这道题,要求的是找到距离每个数字之后更大的数字的最小距离。

如果我们直接用穷举的遍历,我们可以得时间复杂度为O(n2)。时间消耗过高,不可取。

因此,我们利用栈的特性,来对该问题进行实现。
从后往前进行遍历
这种办法是效率最高的一种办法。也就是说,因为我们所要找的是距离最近的较大的,因此,我们从后往前,依次将索引加入到stack中,只要遍历到比当前栈顶元素大的,就将栈顶元素从栈中删除——因为此时栈顶元素已经不是后面的元素所距离的最近的一个,较大的元素了。
因此,栈顶的元素所保存的,一直都是目前来说,索引值最小的当前最大元素的索引。因此,利用这种办法,直接从后往前就可以分别对这些距离进行计算了。

3,代码实现

static const auto s = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    return nullptr;
}();

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& T) {
        int n = T.size();
        stack<int> st;
        vector<int> res (n, 0);
        for(int i = n-1;i >= 0;i--){
            while(!st.empty() && T[i] >= T[st.top()])
                st.pop();
            if(!st.empty())
                res[i] = st.top() - i;
            st.push(i);
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值