算法训练第十一天

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
        
相关推荐
凌肖战1 小时前
力扣网编程55题:跳跃游戏之逆向思维
算法·leetcode
88号技师2 小时前
2025年6月一区-田忌赛马优化算法Tianji’s horse racing optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
ゞ 正在缓冲99%…2 小时前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
Kaltistss3 小时前
98.验证二叉搜索树
算法·leetcode·职场和发展
知己如祭3 小时前
图论基础(DFS、BFS、拓扑排序)
算法
mit6.8243 小时前
[Cyclone] 哈希算法 | SIMD优化哈希计算 | 大数运算 (Int类)
算法·哈希算法
c++bug3 小时前
动态规划VS记忆化搜索(2)
算法·动态规划
哪 吒3 小时前
2025B卷 - 华为OD机试七日集训第5期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
努力写代码的熊大4 小时前
单链表和双向链表
数据结构·链表
军训猫猫头4 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net