<代码随想录> 算法训练营-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
           
相关推荐
To_OC3 小时前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安8 小时前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
七牛开发者11 小时前
MCP 到底是什么?为什么 Agent 都想接上它
算法·aigc·agent
kisshyshy17 小时前
从递归到迭代,一文吃透二叉树的核心知识与 JavaScript 实现
javascript·算法·代码规范
To_OC1 天前
LC 49 字母异位词分组:想到哈希表很简单,选对 key 才是精髓
javascript·算法·leetcode
用户938515635071 天前
从 O(n²) 到 O(nlogn):一文读懂快速排序的“快”与“妙”
javascript·算法
To_OC1 天前
手写快排次次翻车?别死背快排模板了,这才是面试官想听的底层逻辑
javascript·算法·排序算法
饼干哥哥1 天前
Reddit VOC调研太慢?搭一个AI专家团队半小时洞察任何品类|以猫用饮水机为例
人工智能·算法·ai编程