【代码随想录】栈

一刷时间: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
相关推荐
Tadecanlan12 分钟前
[C++面试] 智能指针面试点(重点)续4
开发语言·c++·面试
创新技术阁12 分钟前
FastAPI 的两大核心组件:Starlette 和 Pydantic 详解
后端·python
关山月14 分钟前
被低估的服务器发送事件(SSE)
python
快乐点吧22 分钟前
【Word】批注一键导出:VBA 宏
开发语言·c#·word
DeepLink32 分钟前
Python小练习系列:学生信息排序(sorted + key函数)
python·求职
项目申报小狂人36 分钟前
CUDA详细安装及环境配置——环境配置指南 – CUDA+cuDNN+PyTorch 安装
人工智能·pytorch·python
胡乱儿起个名40 分钟前
C++的指针数组、数组指针和指针数组指针
开发语言·c++
kill bert1 小时前
第32周Java微服务入门 微服务基础
java·开发语言·微服务
学c真好玩1 小时前
4.1-python操作wrod/pdf 文件
开发语言·python·pdf
姜行运1 小时前
数据结构【链表】
c语言·开发语言·数据结构·链表