【代码随想录】栈

一刷时间: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
相关推荐
编程乐趣几秒前
一文掌握DeepSeek本地部署+Page Assist浏览器插件+C#接口调用+局域网访问!全攻略来了!
开发语言·c#
java1234_小锋5 分钟前
一周学会Flask3 Python Web开发-response响应格式
开发语言·python·flask·flask3
Jelena157795857926 分钟前
使用Java爬虫获取1688 item_get_company 接口的公司档案信息
java·开发语言·爬虫
大数据追光猿6 分钟前
Python中的Flask深入认知&搭建前端页面?
前端·css·python·前端框架·flask·html5
java1234_小锋7 分钟前
一周学会Flask3 Python Web开发-flask3模块化blueprint配置
开发语言·python·flask·flask3
莫忘初心丶9 分钟前
python flask 使用教程 快速搭建一个 Web 应用
前端·python·flask
我是苏苏32 分钟前
C#基础:使用Linq进行简单去重处理(DinstinctBy/反射)
开发语言·c#·linq
小小码农(找工作版)34 分钟前
C#前端开发面试题
开发语言·c#
不爱学英文的码字机器41 分钟前
Python爬虫实战:从零到一构建数据采集系统
开发语言·爬虫·python
我是哈哈hh41 分钟前
【JavaScript进阶】作用域&解构&箭头函数
开发语言·前端·javascript·html