day11第五章 栈与队列part02

150. 逆波兰表达式求值

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for item in tokens:
            if item in {'+','-','*','/'}:
                num2 = stack.pop()
                num1 = stack.pop()
                if item == '+':
                    res = num1+num2
                elif item == '-':
                    res = num1-num2
                elif item == '*':
                    res = num1*num2
                else:
                    res = int(num1/num2)
                stack.append(res)
            else:
                stack.append(int(item))
        return stack.pop()

239. 滑动窗口最大值

单调队列

from collections import deque
class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        monoq = MonoQueue()
        max_q = []

        # initialize monoq
        for i in range(k):
            monoq.push(nums[i])
        max_q.append(monoq.front())

        # slide the window
        for i in range(len(nums)-k):
            monoq.pop(nums[i])
            monoq.push(nums[i+k])
            max_q.append(monoq.front())
        
        return max_q

            





class MonoQueue:
    def __init__(self) -> None:
        self.queue = deque()

    def push(self, val: int) -> None:
        while self.queue and self.queue[-1] < val:
            self.queue.pop()
        self.queue.append(val)

    def pop(self, val: int) -> int:
        if self.queue[0] == val:
            return self.queue.popleft()
        else:
            return

    def front(self) -> int:
        return self.queue[0]

        

347.前 K 个高频元素

优先级队列:大顶堆/小顶堆

import heapq
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        # get the frequency
        map_ = defaultdict(int)
        for num in nums:
            map_[num] += 1

        # construct a heaq to sort the frequency
        pri_que = []
        for key, value in map_.items():
            heapq.heappush(pri_que,(value, key)) # add pair(value, key) and sort the heap according to value
            if len(pri_que)>k:
                heapq.heappop(pri_que)
        
        res = []
        for value, key in pri_que:
            res.append(key)

        return res
        

        

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值