<代码随想录> 算法训练营-2024.12.30

今日专题:单调栈

739. 每日温度
python 复制代码
class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        #单调栈
        size=len(temperatures)
        st=[]
        res=[0]*size
        for i in range(len(temperatures)-1,-1,-1):
            while len(st)>0 and temperatures[i]>=temperatures[st[-1]]:
                st.pop()
            if len(st)>0:
                res[i]=st[-1]-i
            st.append(i)
        return res

        
496. 下一个更大元素 I
python 复制代码
class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # 1.在nums2中找到nums1[i]的位置j
        # 2. 找到j后面的第一个更大元素
        #直接先维护出nums2中每个元素的后一个元素
        st=[]
        dict={}
        size=len(nums2)
        for i,n in enumerate(reversed(nums2)):
            while len(st)>0 and n>=st[-1]:
                st.pop()
            if len(st)>0:
                dict[n]=st[-1]
            else:
                dict[n]=-1
            st.append(n)
        res=[]
        for n in nums1:
            res.append(dict[n])
        return res
503. 下一个更大元素 II
python 复制代码
class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        #拷贝一个数组拼到原数组后面
        size=len(nums)
        nums=nums+nums[::]
        st=[]
        res=[-1]*size
        for i in range(len(nums)-1,-1,-1):
            while len(st)>0 and nums[i]>=st[-1]:
                st.pop()
            if len(st)>0 and i<size:
                res[i]=st[-1]
            st.append(nums[i])
        return res
           
相关推荐
木心月转码ing2 小时前
Hot100-Day14-T33搜索旋转排序数组
算法
会员源码网4 小时前
内存泄漏(如未关闭流、缓存无限增长)
算法
颜酱5 小时前
从0到1实现LFU缓存:思路拆解+代码落地
javascript·后端·算法
颜酱6 小时前
从0到1实现LRU缓存:思路拆解+代码落地
javascript·后端·算法
CoovallyAIHub1 天前
Moonshine:比 Whisper 快 100 倍的端侧语音识别神器,Star 6.6K!
深度学习·算法·计算机视觉
CoovallyAIHub1 天前
速度暴涨10倍、成本暴降6倍!Mercury 2用扩散取代自回归,重新定义LLM推理速度
深度学习·算法·计算机视觉
CoovallyAIHub1 天前
实时视觉AI智能体框架来了!Vision Agents 狂揽7K Star,延迟低至30ms,YOLO+Gemini实时联动!
算法·架构·github
CoovallyAIHub1 天前
开源:YOLO最强对手?D-FINE目标检测与实例分割框架深度解析
人工智能·算法·github
CoovallyAIHub1 天前
OpenClaw:从“19万星标”到“行业封杀”,这只“赛博龙虾”究竟触动了谁的神经?
算法·架构·github