前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T27-每日温度

【leetcode刷题】T27-每日温度

作者头像
木又AI帮
修改2019-07-18 09:53:52
5970
修改2019-07-18 09:53:52
举报
文章被收录于专栏:木又AI帮

【英文题目】(学习英语的同时,更能理解题意哟~)

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

【中文题目】

根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高的天数。如果之后都不会升高,请输入 0 来代替。

例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]

提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的都是 [30, 100] 范围内的整数。

【思路】

本题和【T25-下一个更大元素 I】【T26-下一个更大元素 II】基本类似,使用栈保持栈顶元素到栈底元素从小到大,当遍历元素e时,若e大于栈顶元素,则弹出栈,并计算天数,否则压入栈。

值得注意的是:一定要使用while循环对元素e和栈顶元素的大小进行判断,而不是只判断一次。

【代码】

python版本

代码语言:javascript
复制
class Solution(object):
    def dailyTemperatures(self, T):
        """
        :type T: List[int]
        :rtype: List[int]
        """
        res = [] * len(T)
        ls = []
        for i, Ti in enumerate(T):
            while len(ls) >  and T[ls[-1]] < Ti:
                j = ls.pop()
                res[j] = i - j
            ls.append(i)
        return res

C++版本

代码语言:javascript
复制
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& T) {
        stack<int> ls;
        ls.push();
        vector<int> res(T.size(), );
        for(int i=; i<T.size(); i++){
            while(ls.size() >  && T[ls.top()] < T[i]){
                int j = ls.top();
                ls.pop();
                res[j] = i-j;
            }
            ls.push(i);
        }
        return res;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-04-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档