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.
思路:
一开始肯定想到用一个currentMin来记住最小。这种方法不行是因为不支持连续的getMin()操作,因为不知道再之前最小的值。所以方法1就是用一个同等大小的栈来记录当前所有存储元素的最小值就行了。
方法1: 双栈
https://www.youtube.com/watch?v=5h42eila268
易错点:
- pop时候两栈都要pop
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if (helper.empty() || x < helper.top() ) helper.push(x);
else helper.push(helper.top());
st.push(x);
}
void pop() {
st.pop();
helper.pop();
}
int top() {
return st.top();
}
int getMin() {
return helper.top();
}
private:
stack<int> st, helper;
};
改进:
如果x > top(), 不用向helperStack里面推。这个方法对于increasing order只需要推一次,但如果是个decreasing序列空间复杂度并不改变。
方法2: 单栈
思路:
这个方法是在每次更替最小值时候,将previous_min先推进去。举例子:
[“MinStack”,“push”,“push”,“push”,“push”, “push”, “push”, “getMin”,“pop”,“top”,“getMin”]
[[],[-2],[0],[-3],[-5], [-3], [-1],[],[],[],[]]
stack [-2, 0, -2, -3, -3, -5, -3, -1 ]
push [ _, _, __, (^ *), (^ * ), _`]
min_val[ -2, -2, -2, -3, -5, -5, -5]
当pop出元素时,如果栈顶元素不等于min_val时,直接pop掉。如果栈顶元素等于当前min_val, 再之前一个元素是previous_min, 取回代替min_val 之后再pop掉一次。多存的一个元素只用来retrieve之前左右元素的最小值,只在pop时候使用一次就扔掉了。
易错点:
- 当x <= min_val, 更替,多push一次
- 当pop出的元素 = min_val,多pop一次
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
min_val = INT_MAX;
}
void push(int x) {
if (x <= min_val) {
st.push(min_val);
min_val = x;
}
st.push(x);
}
void pop() {
int val = st.top();
st.pop();
if (val == min_val) {
min_val = st.top();
st.pop();
}
}
int top() {
return st.top();
}
int getMin() {
return min_val;
}
private:
stack<int> st;
int min_val;
};