剑指offer30-AcWing-41. 包含min函数的栈
设计一个支持push,pop,top等操作并且可以在O(1)时间内检索出最小元素的堆栈。
- push(x)–将元素x插入栈中
- pop()–移除栈顶元素
- top()–得到栈顶元素
- getMin()–得到栈中最小元素
样例
MinStack minStack = new MinStack();
minStack.push(-1);
minStack.push(3);
minStack.push(-4);
minStack.getMin(); --> Returns -4.
minStack.pop();
minStack.top(); --> Returns 3.
minStack.getMin(); --> Returns -1.
思路:
两个栈实现,其中一个栈存放正常的数值,一个栈存放到目前位置,数值的最小值。
C++ code:
class MinStack {
public:
/** initialize your data structure here. */
stack<int> s_num;
stack<int> small_num;
MinStack() {
}
void push(int x) {
s_num.push(x);
if(small_num.empty() || small_num.top() > x){
small_num.push(x);
}else{
small_num.push(small_num.top());
}
}
void pop() {
s_num.pop();
small_num.pop();
}
int top() {
return s_num.top();
}
int getMin() {
return small_num.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 code:
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.small_num = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack.append(x)
if len(self.small_num) == 0 or self.small_num[-1] > x:
self.small_num.append(x)
else:
self.small_num.append(self.small_num[-1])
def pop(self):
"""
:rtype: void
"""
self.stack.pop()
self.small_num.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.small_num[-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()