<代码随想录> 算法训练营-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 小时前
用c++使输入的数字各个位上数字反转得到一个新数
开发语言·c++·算法
散峰而望1 小时前
C/C++输入输出初级(一) (算法竞赛)
c语言·开发语言·c++·算法·github
Kuo-Teng1 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展
fie88891 小时前
基于MATLAB的狼群算法实现
开发语言·算法·matlab
偷偷的卷2 小时前
【算法笔记 11】贪心策略六
笔记·算法
ZPC82102 小时前
FPGA 部署ONNX
人工智能·python·算法·机器人
_w_z_j_3 小时前
爱丽丝的人偶
算法
老前端的功夫3 小时前
Vue2中key的深度解析:Diff算法的性能优化之道
前端·javascript·vue.js·算法·性能优化
yongui478344 小时前
基于深度随机森林(Deep Forest)的分类算法实现
算法·随机森林·分类
是苏浙4 小时前
零基础入门C语言之C语言实现数据结构之单链表经典算法
c语言·开发语言·数据结构·算法