【代码随想录】栈

一刷时间: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
相关推荐
weelinking19 分钟前
【2026】08_Claude与版本控制:Git协作技巧
数据库·人工智能·git·python·数据挖掘·交互·cloudera
踩着两条虫5 小时前
「AI + 低代码」的可视化设计器
开发语言·前端·低代码·设计模式·架构
JoneBB5 小时前
ABAP Webservice连接
运维·开发语言·数据库·学习
scan7246 小时前
智能体多个工具调用
python
2401_867623986 小时前
CSS Flex布局中如何设置子元素间距_掌握gap属性的现代用法
jvm·数据库·python
即使再小的船也能远航6 小时前
【Python】安装
开发语言·python
weixin_421725266 小时前
Linux 编程语言全解析:C、C++、Python、Go、Rust 谁更强?
linux·python·go·c·编程语言
Irissgwe6 小时前
类与对象(三)
开发语言·c++·类和对象·友元
没有梦想的咸鱼185-1037-16636 小时前
AI-Python机器学习、深度学习核心技术与前沿应用及OpenClaw、Hermes自动化编程
人工智能·python·深度学习·机器学习·chatgpt·数据挖掘·数据分析
雪度娃娃6 小时前
转向现代C++——优先选用nullptr而不是0和NULL
开发语言·c++