p3-1:36:00
    方法一:增加属性min每次push的时候与min比较,让min取最小值
    方法二:用一个栈min来保存最小数,当入栈的时候比较Data栈和min栈的栈顶元素,如果data的小则也压如min,否则就压入min的栈顶元素。弹出时Data和min要同步弹出。

    1. public static class MyStack1 {
    2. private Stack<Integer> stackData;
    3. private Stack<Integer> stackMin;
    4. public MyStack1() {
    5. this.stackData = new Stack<Integer>();
    6. this.stackMin = new Stack<Integer>();
    7. }
    8. public void push(int newNum) {
    9. if (this.stackMin.isEmpty()) {
    10. this.stackMin.push(newNum);
    11. } else if (newNum <= this.getmin()) {
    12. this.stackMin.push(newNum);
    13. }
    14. this.stackData.push(newNum);
    15. }
    16. public int pop() {
    17. if (this.stackData.isEmpty()) {
    18. throw new RuntimeException("Your stack is empty.");
    19. }
    20. int value = this.stackData.pop();
    21. if (value == this.getmin()) {
    22. this.stackMin.pop();
    23. }
    24. return value;
    25. }
    26. public int getmin() {
    27. if (this.stackMin.isEmpty()) {
    28. throw new RuntimeException("Your stack is empty.");
    29. }
    30. return this.stackMin.peek();
    31. }
    32. }