Leetcode 739. 每日温度

心路历程:

暴力解很好想到,就是一个On2的双层循环即可,但是会超时。于是第一反应想到了动态规划,这道题的动态规划思路其实本质上有点像那个跳跃游戏,相当于跳着比较从而减少遍历复杂度。

后来从网上发现这道题是经典的单调栈题目,从后向前遍历,当新遇到的值比之前的元素大的时候,就把比它小的全部pop出去。

解法一:单调栈

python 复制代码
class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        # 单调栈
        n = len(temperatures)
        ans = [0] * n
        st = []
        for i in range(n-1, -1, -1):
            while st and temperatures[i] >= temperatures[st[-1]]: st.pop()  # 丢弃掉比当前值小且排在后面的栈中元素
            if st:  # 可能没有比当前元素大的数了
                ans[i] = st[-1] - i
            st.append(i)  # 每个元素都进栈
        return ans  

解法二:动态规划:

python 复制代码
class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        @cache
        def dp(i):  # 第i天的下一个最高温度在几天后
            if i == len(temperatures) - 1: return 0
            if temperatures[i] < temperatures[i+1]:
                return 1
            else:
                k = i + 1
                while k <= len(temperatures) - 1:
                    nextbig = dp(k)
                    if nextbig == 0: break
                    k += nextbig
                    if temperatures[k] > temperatures[i]:
                        return k - i
                return 0
        res = []
        for i in range(len(temperatures)):
            res.append(dp(i))
        return res
相关推荐
octopus_c5 小时前
STL 之 string:auto 与范围 for、常用接口、模拟实现与深浅拷贝
开发语言·c++·算法
文丑颜不良啊16 小时前
LeetCode1941~1960题目解析
java·leetcode
老师我太想进步了202620 小时前
【数据结构-4】算法美学之顺序表
数据结构·算法
风影同志7832420 小时前
编码器是激活函数吗?—— 一个看起来很像、其实不是的类比
算法
UIU11420 小时前
P1481 魔族密码
c++·算法·动态规划
文丑颜不良啊21 小时前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2001~2020题目解析
java·leetcode
加宝的起点雷达1 天前
40 条候选里 38 条来自同一个源,主卡整屏重样
人工智能·算法·创业
秋天的怀念_David1 天前
算法一千零一夜 · 第二十六夜 协议的母语
java·spring boot·算法