JZ20 包含min函数的栈, 辅助栈
包含min函数的栈
http://www.nowcoder.com/questionTerminal/4c776177d2c04c2494f2555c9fcc1e49
解法一:同步辅助栈
import java.util.Stack;
public class Solution {
Stack<Integer> stack=new Stack<>();
Stack<Integer> helper=new Stack<>();
public void push(int node) {
stack.push(node);
if(helper.isEmpty()) helper.push(node);
else helper.push(Math.min(helper.peek(),node));
}
public void pop() {
stack.pop();
helper.pop();
}
public int top() {
return stack.peek();
}
public int min() {
return helper.peek();
}
}解法二:非同步辅助栈
import java.util.Stack;
public class Solution {
Stack<Integer> stack=new Stack<>();
Stack<Integer> helper=new Stack<>();
public void push(int node) {
stack.push(node);
if(helper.isEmpty()||helper.peek()>=node)
helper.push(node);
}
public void pop() {
int t=stack.pop();
if(t==helper.peek()) helper.pop();
}
public int top() {
return stack.peek();
}
public int min() {
return helper.peek();
}
}
Java中栈的推荐使用方法
Deque<T> stack=new ArrayDeque<>();


查看11道真题和解析