在O(1)时间内返回栈的最小值

来源:互联网 发布:帝国时代 知乎 编辑:程序博客网 时间:2024/06/07 13:22

implement a stack which not only has push, pop, but also is able to return the minimum value within O(1) time.

public class NewStack extends Stack<Node> {public void push(Node node) {if (node.getValue() < this.min()) {node.setMin(node.getValue());}super.push(node);}public Node pop() {return super.pop();}public int min() {if (peek() == null) {return MAX_INT;} else {peek().getMin();}}}class Node {int value;int min;public int getValue() {return value;}public int getMin() {return min;}public void setMin(int min) {this.min = min;}}

in the previous approach, the main drawback is that in each node, they have to store the min value, it costs too many spaces. As the minimum value may stay the same if no larger element appears, so we can improve the algorithm above by removing duplicated min values.

public class StackWithMin {Stack<Integer> stack1 = new Stack<Integer>();Stack<Integer> stack2 = new Stack<Integer>();public void push(int value) {if (value <= min()) {stack2.push(value);}stack1.push(value);}public int pop() {if (stack1.peek() == stack2.peek() ) {stack2.pop();}return stack1.pop();}public int min() {if (stack2.peek() == null) {return MAX_INT;} else {return stack2.peek();}}}