zoukankan      html  css  js  c++  java
  • 739. 每日温度



    代码一:暴力超时了。

    class Solution(object):
        # 暴力超时
        def dailyTemperatures(self, T):
            """
            :type T: List[int]
            :rtype: List[int]
            """
            if not T:
                return []
            res = []
            for i in range(len(T)):
                temp = T[i:]
                if not temp:
                    break
                for j in range(1, len(temp)):
                    if temp[j] > T[i]:
                        res.append(j)
                        break
                    if j == len(temp) - 1:
                        res.append(0)
                        break
            res.append(0)
            return res
    

    代码二:单调栈

    思路:

    注意题目说的是更高的气温,而不是最高的气温。因此,只要找到原list中在当前元素后面且比当前元素大的位置的下标,赋值即可。

    class Solution(object):
        # 单调栈。
        # 遍历T,维护一个栈,栈空或者当前元素比栈顶小,则入栈,否则栈顶出栈,并在res中记录栈顶元素位置的答案。
        # 注意栈中存放的应该是每个元素的下标。
        def dailyTemperatures(self, T):
            """
            :type T: List[int]
            :rtype: List[int]
            """
            if not T:
                return []
            lenT = len(T)
            # 返回值
            res = [0] * lenT
            stack = []
            for index, curT in enumerate(T):
                while stack and curT > T[stack[-1]]:
                    temp = stack.pop()
                    res[temp] = index - temp
                stack.append(index)
            return res
    

  • 相关阅读:
    1. Java基础知识
    2. HelloWorld
    3. Java基础语法
    4. Java流程控制
    设计一个有getMin功能的栈
    ASP.NET中Cookies的使用
    用sql语句建表
    Eclipse “cannot be resolved to a type” 错误
    使用java连接sqlserver2008 R2/sqlserver2008
    使用java连接MySQL数据库
  • 原文地址:https://www.cnblogs.com/panweiwei/p/13754815.html
Copyright © 2011-2022 走看看