155 Min Stack [难度:简单] [最小栈] (解法很巧妙)
【题目】
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.
【解题C++】
”in constant time“要求常数时间,也就是说不能通过遍历来寻得最小值。我一开始是想到了设立两个变量,一个记录最小值,一个记录第二小值。但我的代码漏洞很多,当连续pop两次的数字都是最小值时,那两个变量便都不见了。看了下评论,有人用两个栈的办法,但题目要求Design a stack。于是又找了找博客,看到一种非常巧妙的办法~
设立一个变量minNum,用来记录最小值。进栈时,当该元素≤minNum时,将minNum入栈后再将该元素入栈。这样就真正地保存下来了第二小的变量!出栈时,当出栈元素恰好是最小值时,出栈后此时栈顶元素即是第二小值,这时候更新一下minNum就可以啦!
class MinStack {
public:
/** initialize your data structure here. */
stack<int> st;
int minNum;
MinStack() {
//初始化成一个很大的值
minNum = 0x7fffffff;
}
void push(int x) {
//当入栈元素≤最小值时
//一定要加=,因为最小值可以同时有好几个,都要保存下来
if(x<=minNum)
{
//入栈第二小值
st.push(minNum);
//更新最小值
minNum = x;
}
//入栈
st.push(x);
}
void pop() {
int topNum = st.top();
//如果出栈元素恰好为最小值
if(topNum==minNum)
{
//先出栈
st.pop();
//此时的栈顶元素是之前的第二小值,也就是现在的最小值
minNum = st.top();
}
//这里可以是没进入if语句的普通出栈
//也可以是进入if语句后,出栈掉第二小值的副本元素
st.pop();
}
int top() {
return st.top();
}
int getMin() {
return minNum;
}
};
/**
* 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就偷懒直接用的函数min()
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x: int) -> None:
self.stack.append(x)
def pop(self) -> None:
self.stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return min(self.stack)
# 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()