p3-1:36:00
方法一:增加属性min每次push的时候与min比较,让min取最小值
方法二:用一个栈min来保存最小数,当入栈的时候比较Data栈和min栈的栈顶元素,如果data的小则也压如min,否则就压入min的栈顶元素。弹出时Data和min要同步弹出。
public static class MyStack1 {private Stack<Integer> stackData;private Stack<Integer> stackMin;public MyStack1() {this.stackData = new Stack<Integer>();this.stackMin = new Stack<Integer>();}public void push(int newNum) {if (this.stackMin.isEmpty()) {this.stackMin.push(newNum);} else if (newNum <= this.getmin()) {this.stackMin.push(newNum);}this.stackData.push(newNum);}public int pop() {if (this.stackData.isEmpty()) {throw new RuntimeException("Your stack is empty.");}int value = this.stackData.pop();if (value == this.getmin()) {this.stackMin.pop();}return value;}public int getmin() {if (this.stackMin.isEmpty()) {throw new RuntimeException("Your stack is empty.");}return this.stackMin.peek();}}
