<代码随想录> 算法训练营-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
           
相关推荐
蓝斯4979 分钟前
Diff算法的简单介绍
算法
过期的秋刀鱼!13 分钟前
L2正则化,防止过拟合-历史补充
算法·过拟合·l2正则化
hansang_IR1 小时前
【题解】LC:Z 算法(Z Algorithm)
c++·算法·字符串
范什么特西1 小时前
回答知识总结02
算法·哈希算法
橘子汽水1681 小时前
Leetcode 230,98:二叉搜索树中第K小的元素,验证二叉搜索树
算法·leetcode·职场和发展
m沐沐1 小时前
【机器学习】DBSCAN聚类算法——原理、参数调优与实战
人工智能·python·深度学习·算法·机器学习·聚类·dbscan
问商十三载2 小时前
GEO优化的6个核心诊断工具,2026年实操版详解
人工智能·算法·机器学习
手写码匠2 小时前
华为云征文|DeepSeek-R1 智能问数 Agent 实战:Flexus X 实例 + Dify 构建企业级 Text-to-SQL 查询助手
人工智能·深度学习·算法·aigc
mifengxing2 小时前
Java集合与泛型
java·算法·复习笔记
liulilittle3 小时前
[OPENPPP2] ssea 算法详解(中文)
算法·x86·x64·simd·openppp2·ssea·base94