题目
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.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
题意
设计一个栈使它支持push(), pop(), top(),和获取当前最小值的操作。
push(x) -- 添加一个元素到栈中.
pop() -- 删除栈顶元素.
top() -- 获得栈顶元素.
getMin() -- 获取当前栈中最小的元素.
题解
前三个操作用普通的栈操作都可以实现,关键是最后一个获取当前栈的最小的元素,关键在于保存当前栈中每一个元素当年的最小元素。
例如
栈中的元素为-2, 0, -3
-2 位置对应的最小元素为 -2
0 位置对应的最小元素为 -2,
-3 位置对应的最小元素为-3,
即需要保存的元素为-2,-3
即用另一个栈保存最小元素,
需要注意的是当栈执行删除操作时,如果栈顶的元素等于最小栈的元素,则需要删除最小栈顶的元素。
C++代码
class MinStack {
public:
/** initialize your data structure here.
用两个栈,一个用于正常的
*/
stack<int>Stack;
stack<int>minStack;
MinStack()
{
}
void push(int x) {
Stack.push(x);
if(minStack.empty()){
minStack.push(x);
}
else{
if(minStack.top()>=x){
minStack.push(x);
}
}
}
void pop() {
if(Stack.top()==minStack.top()){
Stack.pop();
minStack.pop();
}
else{
Stack.pop();
}
}
int top() {
return Stack.top();
}
int getMin() {
return minStack.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
python代码
python中并没有C++中的stack操作,不过python中有一个结构list可以实现与栈相同的元素。python中关于栈操作的详解:http://python.jobbole.com/87581/
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.minStack = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack.append(x)
if len(self.minStack)==0 or self.minStack[-1]>=x:
self.minStack.append(x)
def pop(self):
"""
:rtype: void
"""
if self.minStack[-1] == self.stack[-1]:
self.minStack.pop()
self.stack.pop()
else:
self.stack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.minStack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()