Leetcode-739. Daily Temperatures

本文针对LeetCode上的一道题目——每日气温问题进行了解析,介绍了一种利用栈来求解的方法。具体步骤包括初始化一个栈来存储位置,逆序遍历温度数组,并通过比较栈顶元素与当前元素的大小来确定答案。

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

Original link: https://leetcode.com/problems/daily-temperatures/

Given a list of daily temperatures, return a list such that tell how many days you would have to wait until a warmer temperature.

Initialize a stack (list) to store position.
Iterate the array T in the reverse sequence, the stack will pop out position where the temperature (T[stack[-1]) is less than the current temperature (T[i]).
The remained last element in stack is the position where the temperature is larger than the current one. If the stack is empty, it means that elements after the current one are all smaller.

Code:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值