【代码随想录】栈

一刷时间:6月8日--6月9日

用栈实现队列

python 复制代码
class MyQueue(object):

    def __init__(self):
        self.stack_in=[]
        self.stack_out=[]

    def push(self, x):
        self.stack_in.append(x)
        
    def pop(self):
        if self.stack_out:
            return self.stack_out.pop()
        else:
            while self.stack_in:
                self.stack_out.append(self.stack_in.pop())
            return self.stack_out.pop()
    
    def peek(self):
        x=self.pop()
        self.stack_out.append(x)
        return x
        
    def empty(self):
        if self.stack_in or self.stack_out:
            return False
        else:
            return True

用队列实现栈

python 复制代码
class MyStack(object):

    def __init__(self):
        self.deque=deque()

    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        self.deque.append(x)


    def pop(self):
        """
        :rtype: int
        """
        return self.deque.pop()


    def top(self):
        """
        :rtype: int
        """
        x=self.deque.pop()
        self.deque.append(x)
        return x


    def empty(self):
        """
        :rtype: bool
        """
        if self.deque:
            return False
        else:
            return True

有效的括号

python 复制代码
 		alpha=[]
        for x in s:
            if x=='(' or x=='[' or x=='{':
                alpha.append(x)
            else:
                if x==')':
                    if len(alpha)==0 or alpha.pop()!='(':
                        return False
                elif x=='}':
                    if len(alpha)==0 or alpha.pop()!='{':
                        return False
                elif  x==']':
                    if len(alpha)==0 or alpha.pop()!='[':
                        return False
        
        if len(alpha)==0:
            return True
        else:
            return False

删除字符串中所有相邻重复项

python 复制代码
 re=[]
        for x in s:
            if len(re)==0:
                re.append(x)
            else:
                if re[-1]==x:
                    re.pop()
                else:
                    re.append(x)
        return "".join(re)

逆波兰表达式求值

使用python评测通过,主要区别就是python和python3在处理除法运算的不同处理

python 复制代码
 nums=[]
        for x in tokens:
            if x=='+' or x=='-' or x=='*' or x=='/':
                x2=int(nums.pop())
                x1=int(nums.pop())
                if x=='+':
                    nums.append(x1+x2)
                elif x=='-':
                    nums.append(x1-x2)
                elif x=='*':
                    nums.append(x1*x2)
                elif x=='/':
                    nums.append(int(float(x1)/x2))
            else:
                nums.append(int(x))
        return nums[0]

使用python3运行通过

python 复制代码
		nums=[]
        for x in tokens:
            if x=='+' or x=='-' or x=='*' or x=='/':
                x2=int(nums.pop())
                x1=int(nums.pop())
                if x=='+':
                    nums.append(x1+x2)
                elif x=='-':
                    nums.append(x1-x2)
                elif x=='*':
                    nums.append(x1*x2)
                elif x=='/':
                    nums.append(int(x1/x2))  #向零取整
            else:
                nums.append(int(x))
        return nums[0]

滑动窗口最大值

基本思想是维持一个最大窗口,判断被弹出和被推入的是否是最大值,进行相应的处理。

本质上应该是n*k的复杂度,超过时间限制了。。。

python 复制代码
 		array=[]
        for i in range(len(nums)-k+1):
            if i-1>=0 and nums[i-1]<array[-1]:
                if i+k-1<len(nums) and nums[i+k-1]<=array[-1]:
                    array.append(array[-1])
                elif i+k-1<len(nums) and nums[i+k-1]>array[-1]: 
                    array.append(nums[i+k-1])
                else:
                    array.append(max(nums[i:i+k]))
            elif i-1>=0 and nums[i-1]==array[-1]:
                if i+k-1<len(nums) and nums[i+k-1]<=nums[i-1]:
                    array.append(max(nums[i:i+k]))
                elif i+k-1<len(nums) and nums[i+k-1]>nums[i-1]:
                    array.append(nums[i+k-1])
            else:
                array.append(max(nums[i:i+k]))
        return array

自定义一个队列,保留可能是最大值的数

python 复制代码
class MyDeque():
    def __init__(self):
        self.deque=deque()
    def pop(self,value):
        if self.deque and self.deque[0]==value:
            self.deque.popleft()
    def push(self,value):
        while self.deque and value>self.deque[-1]:
            self.deque.pop()
        self.deque.append(value)
    def getmax(self):
        return self.deque[0]
        
class Solution(object):
    def maxSlidingWindow(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        mydeque=MyDeque()
        result=[]
        for i in range(k):
            mydeque.push(nums[i])
        result.append(mydeque.getmax())
        for i in range(k,len(nums)):
            mydeque.pop(nums[i-k])
            mydeque.push(nums[i])
            result.append(mydeque.getmax())
        return result
        

前k个高频元素

使用字典统计每个字符出现频率,并使用最小堆维持前k个最大的频率

python 复制代码
  		map_={}
        for i in nums:
            map_[i]=map_.get(i,0)+1
        
        pre_que=[]

        for idx,freq in map_.items():
            heapq.heappush(pre_que,(freq,idx))
            if len(pre_que)>k:
                heapq.heappop(pre_que)
        
        reslut=[]
        for i in range(k):
            reslut.append(heapq.heappop(pre_que)[1])
        return reslut
相关推荐
不当菜虚困6 分钟前
JAVA设计模式——(四)门面模式
java·开发语言·设计模式
ruyingcai6666666 分钟前
用python进行OCR识别
开发语言·python·ocr
Niuguangshuo9 分钟前
Python设计模式:MVC模式
python·设计模式·mvc
TOMGRIL12 分钟前
文件的读取操作
python
m0Java门徒14 分钟前
面向对象编程核心:封装、继承、多态与 static 关键字深度解析
java·运维·开发语言·intellij-idea·idea
liuweidong080216 分钟前
【Pandas】pandas DataFrame radd
开发语言·python·pandas
IT_Octopus21 分钟前
AI工程pytorch小白TorchServe部署模型服务
人工智能·pytorch·python
CodeDevMaster36 分钟前
browser-use:AI驱动的浏览器自动化工具使用指南
python·llm
农民也会写代码1 小时前
dedecms织梦arclist标签noflag属性过滤多个参数
开发语言·数据库·sql·php·dedecms
内网渗透1 小时前
Python 虚拟环境管理:venv 与 conda 的选择与配置
开发语言·python·conda·虚拟环境·venv