Description
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.
分析
题目的意思是:实现MinStack的push,pop,top,tetrieving功能。
- 空间换时间
- 最小栈只不过在原有栈的基础上增加了一个获取最小值的功能,我们可以用两个栈来模拟,第一个栈来模拟正常的栈的功能,第二个栈用来存储栈中的最小值。注意我们在pop和push的一点小小的改变。
C++实现
class MinStack {
private:
stack<int> s1,s2;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
s1.push(x);
if(s2.empty()||x<=s2.top()){
s2.push(x);
}
}
void pop() {
if(s1.top()==s2.top()) s2.pop();
s1.pop();
}
int top() {
return s1.top();
}
int getMin() {
return s2.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版本,s1是主栈,用于接收数据,s2是辅助栈,用于存储最小值。
class MinStack:
def __init__(self):
self.s1 = []
self.s2 = []
def push(self, val: int) -> None:
self.s1.append(val)
if len(self.s2)==0 or val <= self.s2[-1]:
self.s2.append(val)
def pop(self) -> None:
if self.s1[-1]==self.s2[-1]:
self.s2.pop()
self.s1.pop()
def top(self) -> int:
return self.s1[-1]
def getMin(self) -> int:
return self.s2[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()