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
相关推荐
wanzhong233329 分钟前
CUDA学习5-矩阵乘法(共享内存版)
深度学习·学习·算法·cuda·高性能计算
fufu03111 小时前
Linux环境下的C语言编程(四十八)
数据结构·算法·排序算法
Yingye Zhu(HPXXZYY)1 小时前
Solution to Luogu P6340
算法
小熳芋2 小时前
单词搜索- python-dfs&剪枝
算法·深度优先·剪枝
Xの哲學2 小时前
Linux SLAB分配器深度解剖
linux·服务器·网络·算法·边缘计算
bu_shuo2 小时前
MATLAB中的转置操作及其必要性
开发语言·算法·matlab
高洁012 小时前
图神经网络初探(2)
人工智能·深度学习·算法·机器学习·transformer
爱装代码的小瓶子2 小时前
算法【c++】二叉树搜索树转换成排序双向链表
c++·算法·链表
思成Codes2 小时前
数据结构:基础线段树——线段树系列(提供模板)
数据结构·算法
虾..4 小时前
Linux 简单日志程序
linux·运维·算法