leetcode-739 每日温度 Python

本文介绍了三种不同的算法实现方式,用于预测每日气温变化。方法一采用从后往前遍历的策略,方法二利用栈来优化计算过程,而方法三则提出了正向栈的解决方案。这些算法在处理气温预测问题上表现出了高效性和准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:从后往前

class Solution:
    def dailyTemperatures(self, T: List[int]) -> List[int]:
        Next = [float('inf')]*102
        ans = [0] * len(T)
        for i in range(len(T)-1, -1, -1):
            warmer = min(Next[t] for t in range(T[i]+1, 102))
            if warmer < float('inf'):
                ans[i] = warmer - i
            Next[T[i]] = i
        return ans

方法二:栈

class Solution:
    def dailyTemperatures(self, T: List[int]) -> List[int]:
        ans = [0] * len(T)
        stack = []
        for i in range(len(T)-1, -1, -1):
            while stack and T[i] >= T[stack[-1]]:
                stack.pop()
            if stack:
                ans[i] = stack[-1] - i
            stack.append(i)
        return ans

方法三:栈(正向)

class Solution:
    def dailyTemperatures(self, T: List[int]) -> List[int]:
        class Node:
            def __init__(self, t, index):
                self.t = t
                self.index = index
        stack = []
        ans = [0] * len(T)
        for i in range(len(T)):
            while stack and T[i] > stack[-1].t:
                top = stack.pop(-1)
                ans[top.index] = i - top.index
            node = Node(T[i], i)
            stack.append(node)
        while stack:
            top = stack.pop(-1)
            ans[top.index] = 0
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值