算法训练第十一天

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
        
相关推荐
zh_xuan1 小时前
LeeCode 40.组合总和II
c语言·数据结构·算法
都叫我大帅哥2 小时前
动态规划:从懵逼到装逼,一篇让你彻底搞懂DP的终极指南
java·算法
wangluoqi2 小时前
c++ 数据结构-并查集、ST表 小总结
数据结构·c++
艾莉丝努力练剑3 小时前
《递归与迭代:从斐波那契到汉诺塔的算法精髓》
c语言·学习·算法
超级皮皮8 小时前
力扣热题之stack
算法·leetcode·职场和发展
weixin_470740368 小时前
某算法的python执行汇编
汇编·python·算法
是乐谷9 小时前
燧原科技招大模型训练算法工程师
科技·算法
YuTaoShao9 小时前
【LeetCode 热题 100】139. 单词拆分——(解法一)记忆化搜索
java·算法·leetcode·职场和发展
小马学嵌入式~11 小时前
数据结构:队列 二叉树
c语言·开发语言·数据结构·算法
焊锡与代码齐飞12 小时前
嵌入式第三十五课!!Linux下的网络编程
linux·运维·服务器·开发语言·网络·学习·算法