<代码随想录> 算法训练营-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
           
相关推荐
卷福同学1 小时前
【AI编程】AI+高德MCP不到10分钟搞定上海三日游
人工智能·算法·程序员
mit6.8241 小时前
[Leetcode] 预处理 | 多叉树bfs | 格雷编码 | static_cast | 矩阵对角线
算法
皮卡蛋炒饭.2 小时前
数据结构—排序
数据结构·算法·排序算法
??tobenewyorker3 小时前
力扣打卡第23天 二叉搜索树中的众数
数据结构·算法·leetcode
贝塔西塔3 小时前
一文读懂动态规划:多种经典问题和思路
算法·leetcode·动态规划
众链网络3 小时前
AI进化论08:机器学习的崛起——数据和算法的“二人转”,AI“闷声发大财”
人工智能·算法·机器学习
4 小时前
Unity开发中常用的洗牌算法
java·算法·unity·游戏引擎·游戏开发
飒飒真编程5 小时前
C++类模板继承部分知识及测试代码
开发语言·c++·算法
GeminiGlory5 小时前
算法练习6-大数乘法(高精度乘法)
算法
熬了夜的程序员5 小时前
【华为机试】HJ61 放苹果
算法·华为·面试·golang