算法训练第十一天

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
        
相关推荐
workflower6 小时前
单元测试-例子
java·开发语言·算法·django·个人开发·结对编程
MicroTech20258 小时前
微算法科技(MLGO)研发突破性低复杂度CFG算法,成功缓解边缘分裂学习中的掉队者问题
科技·学习·算法
墨染点香8 小时前
LeetCode 刷题【126. 单词接龙 II】
算法·leetcode·职场和发展
aloha_7899 小时前
力扣hot100做题整理91-100
数据结构·算法·leetcode
Tiny番茄9 小时前
31.下一个排列
数据结构·python·算法·leetcode
挂科是不可能出现的9 小时前
最长连续序列
数据结构·c++·算法
_Aaron___9 小时前
List.subList() 返回值为什么不能强转成 ArrayList
数据结构·windows·list
前端小L10 小时前
动态规划的“数学之魂”:从DP推演到质因数分解——巧解「只有两个键的键盘」
算法·动态规划
RTC老炮10 小时前
webrtc弱网-ReceiveSideCongestionController类源码分析及算法原理
网络·算法·webrtc
21号 110 小时前
9.Redis 集群(重在理解)
数据库·redis·算法