题目
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
提示:
各函数的调用总次数不超过 20000 次
C++
class MinStack {
public:
/** initialize your data structure here. */
stack<int>s;
stack<int>min_s;
MinStack() {
while(!min_s.empty()) min_s.pop();
while(!s.empty()) s.pop();
min_s.push(INT_MAX);
}
void push(int x) {
s.push(x);
min_s.push(::min(x,min_s.top()));
}
void pop() {
min_s.pop();
s.pop();
}
int top() {
return s.top();
}
int min() {
return min_s.top();
}
};
//经验:::min的意思是全局作用域符号,当全局变量在局部函数中与其中某个变量重名,那么就可以用::来区分
/**
* 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->min();
*/
Python
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.minstack = []
self.minstack.append(sys.maxint)
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.stack.append(x)
self.minstack.append(min(x, self.minstack[-1]))
def pop(self):
"""
:rtype: None
"""
self.stack.pop()
self.minstack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def min(self):
"""
:rtype: int
"""
return self.minstack[-1]
#经验:1.top用stack[-1]表示 2.最大int可以用sys.maxint表示
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.min()