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.
类似的在cracking the code interview里面有用两个queue模拟stack的题目
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()