Min Stack Leetcode Python

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.


push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.

getMin() -- Retrieve the minimum element in the stack.

这题考察用两个stack 去main一个最小的stack.

stack1用来maintain stack2就是所要的保持最小的那个stack.

push的时候 stack1一直进 当stack2为空或者进的数小于等于stack2时就进。

pop的时候比较stack1一直pop 当pop的值和stack2[-1]一样大的时候stack2也pop.

top就是stack1[-1]

getmin就是stack2[-1]

代码如下:

class MinStack:
    # @param x, an integer
    # @return an integer
    def __init__(self):
        self.stack1=[]
        self.stack2=[]
    def push(self, x):
        self.stack1.append(x)
        if len(self.stack2)==0 or x<=self.stack2[-1]:
            self.stack2.append(x)
        
    # @return nothing
    def pop(self):
        top=self.stack1[-1]
        self.stack1.pop()
        if top==self.stack2[-1]:
            self.stack2.pop()

    # @return an integer
    def top(self):
        return self.stack1[-1]        

    # @return an integer
    def getMin(self):
        return self.stack2[-1]
        

类似的在cracking the code interview里面有用两个queue模拟stack的题目

主题思想是

push

所有东西往queue1丢,

pop

先把que1的东西都放到queue2里面然后再出que.



代码如下:

class mystack:
    def __init__(self):
        self.que1=[]
        self.que2=[]
    def push(self,val):
        self.que1.append(val)
        print 'push',val
    def pop(self):
        while len(self.que1)>0:
            self.que2.append(self.que1.pop())
        self.que2[0]
        print 'pop',self.que2[0]
        return self.que2.pop(0)    


stack=mystack()
stack.push(1)
stack.push(2)
stack.pop()
stack.pop()


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值