算法训练第十一天

150. 逆波兰表达式求值

代码:

python 复制代码
class Solution(object):
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        stack = []
        for i in tokens:
            if i=='+':
                b = int(stack.pop())
                a = int(stack.pop())
                stack.append(a+b)
            elif i=='-':
                b = int(stack.pop())
                a = int(stack.pop())
                stack.append(a-b)
            elif i=='*':
                b = int(stack.pop())
                a = int(stack.pop())
                stack.append(a*b)
            elif i == '/':
                b = int(stack.pop())
                a = int(stack.pop())
                if a * b < 0:
                    res = abs(a)//abs(b)
                    stack.append(-res)
                else:
                    stack.append(a // b)
            else:
                stack.append(int(i))
        return int(stack[0])
        

239. 滑动窗口最大值

代码:

python 复制代码
class Queue:
    def __init__(self):
        self.arr = []

    def add(self,x):
        while len(self.arr)>0 and self.arr[len(self.arr)-1]<x:
            self.arr.pop()
        self.arr.append(x)
        
        
    def delete(self, x):
        if self.arr[0] == x:
            self.arr.pop(0)


    def get_max(self):
        return self.arr[0]


class Solution(object):
    def maxSlidingWindow(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        ans = []
        queue = Queue()
        i = 0
        j = 0
        while j< len(nums):
            queue.add(nums[j])
            if j-i>=k:
                queue.delete(nums[i])
                i+=1
            if j-i+1>=k:
                ans.append(queue.get_max())
            
            j+=1
        return ans

347.前 K 个高频元素

代码:

python 复制代码
class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        nums.sort()
        di = {}
        for i in nums:
            if di.get(i):
                di[i]+=1
            else:
                di[i]=1
        di_items = di.items()
        res = sorted(di_items, key=lambda x: x[1], reverse=True)
        ans = []
        for i in res:
            ans.append(i[0])
            if len(ans)==k:
                return ans
        
相关推荐
啊董dong4 分钟前
noi-2026年5月12号小测验
数据结构·c++·算法
不知名的忻5 分钟前
红黑树(简易版)
算法·红黑树
NQBJT7 分钟前
万字拆解 NeckFix:AI 脖子前倾检测的算法原理与工程实现
人工智能·算法
jaychouchannel11 分钟前
Python 常用排序算法详解
算法
数智工坊13 分钟前
【Inner Monologue论文阅读】: 首次将大语言模型嵌入机器人控制闭环,实现自我反思和动态行为调整
论文阅读·人工智能·算法·语言模型·机器人·无人机
南境十里·墨染春水38 分钟前
数据结构 —— 链表
数据结构·链表
为何创造硅基生物1 小时前
C 语言 typedef 结构体私有化
c语言·开发语言·算法
yzx9910131 小时前
递归算法入门:像俄罗斯套娃一样思考
人工智能·算法
心中有国也有家1 小时前
从零上手 CANN 学习中心:像逛技术便利店一样学昇腾
学习·算法·开源
oo哦哦1 小时前
搜索矩阵系统的最短路密码:用Dijkstra算法和网络流理论,解释为什么你做了1000个关键词,流量还不如别人30个
网络·算法·矩阵