# 剑指 Offer 30. 包含min函数的栈

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.min();   --> 返回 -2.


# 解法1 一个栈

min()方法的效率比较低，就是挨个比较。

class MinStack {

Stack<Integer> stack = null;

/** initialize your data structure here. */
public MinStack() {
stack = new Stack<>();
}

public void push(int x) {
stack.push(x);
}

public void pop() {
stack.pop();
}

public int top() {
return stack.peek();
}

public int min() {

int min = Integer.MAX_VALUE;

for (Integer integer : stack) {
if(min > integer)
min = integer;
}

return 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();
*/


# 解法2 双栈

class MinStack {

Stack<Integer> stack = null;
Stack<Integer> stackB = null;

/** initialize your data structure here. */
public MinStack() {
stack = new Stack<>();
stackB = new Stack<>();
}

public void push(int x) {
stack.push(x);
if(stackB.isEmpty() || stackB.peek() >= x)
stackB.push(x);
}

public void pop() {
if(stack.pop().equals(stackB.peek()))
stackB.pop();
}

public int top() {
return stack.peek();
}

public int min() {
return stackB.peek();
}

}

/**
* 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();
*/


02-20 125
04-08 52
08-28 111
06-06 237
10-29 115
04-23 56
03-19 92
09-29