算法训练第十一天

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
        
相关推荐
程序员buddha2 小时前
C语言数组详解
c语言·开发语言·算法
蒙奇D索大3 小时前
【算法】递归算法的深度实践:从布尔运算到二叉树剪枝的DFS之旅
笔记·学习·算法·leetcode·深度优先·剪枝
卡提西亚4 小时前
C++笔记-25-函数模板
c++·笔记·算法
ghie90904 小时前
MATLAB/Simulink水箱水位控制系统实现
开发语言·算法·matlab
多多*4 小时前
分布式系统中的CAP理论和BASE理论
java·数据结构·算法·log4j·maven
yuan199974 小时前
基于粒子群优化(PSO)算法的PID控制器参数整定
算法
小白程序员成长日记5 小时前
2025.11.10 力扣每日一题
数据结构·算法·leetcode
hoiii1875 小时前
基于交替方向乘子法(ADMM)的RPCA MATLAB实现
人工智能·算法·matlab
fengfuyao9855 小时前
MATLAB的加权K-means(Warp-KMeans)聚类算法
算法·matlab·kmeans
循环过三天6 小时前
3.1、Python-列表
python·算法