## [LeetCode] 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++ 解法一：

```class MinStack {
public:
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();
}

private:
stack<int> s1, s2;
};```

Java 解法一：

```public class MinStack {
private Stack<Integer> s1 = new Stack<>();
private Stack<Integer> s2 = new Stack<>();

public MinStack() {}
public void push(int x) {
s1.push(x);
if (s2.isEmpty() || s2.peek() >= x) s2.push(x);
}
public void pop() {
int x = s1.pop();
if (s2.peek() == x) s2.pop();
}
public int top() {
return s1.peek();
}
public int getMin() {
return s2.peek();
}
}```

C++ 解法二：

```class MinStack {
public:
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 t = st.top(); st.pop();
if (t == min_val) {
min_val = st.top(); st.pop();
}
}
int top() {
return st.top();
}
int getMin() {
return min_val;
}
private:
int min_val;
stack<int> st;
};```

Java 解法二：

```public class MinStack {
private int min_val = Integer.MAX_VALUE;
private Stack<Integer> s = new Stack<>();

public MinStack() {}
public void push(int x) {
if (x <= min_val) {
s.push(min_val);
min_val = x;
}
s.push(x);
}
public void pop() {
if (s.pop() == min_val) min_val = s.pop();
}
public int top() {
return s.peek();
}
public int getMin() {
return min_val;
}
}```

Github 同步地址：

https://github.com/grandyang/leetcode/issues/155

Sliding Window Maximum

Max Stack

https://leetcode.com/problems/min-stack/

https://leetcode.com/problems/min-stack/discuss/49014/java-accepted-solution-using-one-stack

https://leetcode.com/problems/min-stack/discuss/49016/c-using-two-stacks-quite-short-and-easy-to-understand