Leetcode 栈知识点总结

本文总结了LeetCode中涉及栈的多个题目,包括Daily Temperatures、Next Greater Element、Baseball Game等,并介绍了如何利用栈解决行星碰撞、实现特定遍历顺序、栈实现队列等问题,涉及二叉树遍历、后缀表达式求值和路径简化等应用场景。
摘要由CSDN通过智能技术生成

来看下Leetcode中Tag为Stack的题目

  • [Leetcode 739] Daily Temperatures:求下一个温暖天气距离当前日期的时间差。Medium
class Solution(object):
    def dailyTemperatures(self, temperatures):
        """
        :type temperatures: List[int]
        :rtype: List[int]
        """
        size,stack = len(temperatures),[]
        ret = [0]*size
        for idx,tem in enumerate(temperatures):
            while(stack and temperatures[stack[-1]]<tem):
                idj = stack.pop()
                ret[idj]=idx-idj
            stack.append(idx)
        return ret
  • [Leetcode 496] Next Greater Element I:给定两个数组(无重复)nums1 与 nums2,其中nums1的元素是nums2的子集。在nums2中寻找大于nums1中对应位置且距离最近的元素。如果对应位置不存在这样的元素,则输出-1。Easy
    思路:用stack维护一个递减序列,当num>stack[-1] 时 弹出stack[-1]同时表示num是弹出的值的下一个大元素
class Solution(object):
    def nextGreaterElement(self, findNums, nums):
        """
        :type findNums: List[int]
        :type nums: List[int]
        :rtype: List[int]
        """
        dmap,stack = {},[]
        for num in nums:
            while stack and stack[-1]<num:
                dmap[stack.pop()]=num
            stack.append(num)
        return [dmap.get(n,-1) for n in findNums]
  • [Leetcode 503] Next Greater Element II:求循环数组的最近较大值。Medium
    思路:其实和前一题一样,因为是循环数组,对数组进行拼接再操作即可
class Solution(object):
    def nextGreaterElements(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        size,stack = len(nums),[]
        ret = [-1]*size
        nums = nums+nums
        for idx,num in enumerate(nums):
            while stack and nums[stack[-1]]<num:
                idj = stack.pop()
                if idj<size: ret[idj]=num
            stack.append(idx)
        return ret
  • [Leetcode 682] Baseball Game:一个数组,数字字符表示当局得分,’C’表示上一局得分无效,’D’表示上一局得分翻倍,‘+’表示得分前两局之和,求总的分数,Easy
class Solution(object):
    def calPoints(self, ops):
        """
        :type ops: List[str]
        :rtype: int
        """
        stack = []
        for op in ops:
            if op=='C':
                stack.pop()
            elif op=='D':
                stack.append(stack[-1]*2)
            elif op=='+':
                stack.append(stack[-1]+stack[-2])
            else:
                stack.append(int(op))
        return sum(stack)
  • [Leetcode 735] Asteroid Collision:行星碰撞问题。+,-表示方向,大小表示质量,若发生碰撞,则保留大质量的行星,若两行星质量相同,则一起消失。Medium
class Solution(object):
    def asteroidCollision(self, asteroids):
        """
        :type asteroids: List[int]
        :rtype: List[int]
        """
        stack = []
        for asteroid in asteroids:
            flag = True
            while(stack and stack[-1]>0 and asteroid<0 and flag):
                if -asteroid>stack[-1]: stack.pop()
                else:
                    flag = False
                    if -asteroid==stack[-1]: stack.pop()
            if flag:  stack.append(asteroid)
        return stack
  • [Leetcode 636] Exclusive Time of Functions:给定一组函数调用日志,格式为”function_id:start_or_end:timestamp”,函数可以递归。求每个函数调用的总时长。Medium
    思路:这题其实巧妙在栈顶元素的变化。如果有新的函数进来,可以先计算stack[-1] 的调用时间,如果当前函数执行完毕,trick在stack[-1][1] = logtime+1,即记录成当前stack[-1]重新执行的时间
class Solution(object):
    def exclusiveTime(self, n, logs):
        """
        :type n: int
        :type logs: List[str]
        :rtype: List[int]
        """
        stack,ans = [],[0 for i in range(n)]
        for log in logs:
            logname,state,logtime = log.split(':')
            logname,logtime = int(logname),int(logtime)
            if state == 'start':
                if len(stack):
                    ans[stack[-1][0]]+=logtime-stack[-1][1]
                stack.append([logname,logtime])
            else:
                lastitem = stack.pop()
                ans[lastitem[0]]+=logtime-lastitem[1]+1
                if len(stack):
                    stack[-1][1]=logtime+1
        return ans
class MyQueue(object):
    def 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值