LeetCode 739. Daily Temperatures - 单调栈(Monotonic Stack)系列题3

该博客讨论了如何使用单调栈解决LeetCode 739问题,即根据每日气温数组计算等待更高温度的天数。博主解释了题目的要求,将问题转化为寻找下一个更大数的问题,并详细阐述了解题思路:保持单调递减栈,遍历数组并根据栈内元素与当前元素的关系更新答案,最后给出遍历结束后栈内元素的处理方法。

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

Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

Example 1:

Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]

Example 2:

Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]

Example 3:

Input: temperatures = [30,60,90]
Output: [1,1,0]

Constraints:

  • 1 <= temperatures.length <= 105
  • 30 <= temperatures[i] <= 100

题目大意是给定一个数组,里面的数值表示每天的气温,对于数组中的每一天要求算出当前天之后需要等待多少天才能等到气温比当前天高的那一天,要是数组中不存在这样的一天答案为0天。

这道题其实就是求下一个更大数(Next Greater Number),只是被包装成气温相关的问法。换种问法就是,给定一个数组,对于数组中每个数,要求找出当前数(索引为i)的下一个更大数(索引为j)与当前数的距离(j - i),如不存在下个更大数那么距离为0。解法跟496. Next Greater Element I503. Next Greater Element II一样,都是用单调递减栈。

定义一个堆栈要始终维持栈是单调递减的,遍历数组temperature,当栈为空或者当前数比栈顶的数小时,就把当前数值压入栈(注:由于答案要求距离,所以压入栈的是当前数的索引值);当遇到当前数比栈顶的数大时,就把栈中从栈顶开始所有比当前数小的数都弹出栈,当前数就是所有被弹出栈的数的下一个更大数,计算二者在数组中的距离存入答案,最后把当前数压入栈。遍历完这个数组后,栈里面剩下的数都不存在下一个更大数。

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        n = len(temperatures)
        res = [0] * n
        st = []
        
        for i in range(n):
            while st and temperatures[st[-1]] < temperatures[i]:
                j = st.pop()
                res[j] = i - j
            st.append(i)
        
        return res

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值