1. 程式人生 > >演算法--設計一個有getMin功能的棧

演算法--設計一個有getMin功能的棧

//本文程式碼出自 左程雲 的《程式設計師程式碼面試指南》

/** 1.設計一個有getMin功能的棧
*   題目:實現一個特殊的棧,在實現棧的基本功能的基礎上,再實現返回棧中最小元素的操作。
*   要求:pop、push、getMin操作的時間複雜度都是O(1).
*   設計的棧型別可以使用現有的棧結構
*
*   只儲存當前最小值,空間少,但彈出時慢
*/
public class MyStack1 {
    private Stack<Integer> stackData;
    private Stack<Integer> stackMin;
    //初始化
public MyStack1() { stackData=new Stack<Integer>(); stackMin=new Stack<Integer>(); } //壓入 public void push(int newNum){ if(stackMin.isEmpty()||newNum<=this.getMin()){ stackMin.push(newNum); } stackData.push(newNum); } //彈出
public int pop(){ if(stackData.isEmpty()){ throw new RuntimeException("Your stack is empty!"); } int value =stackData.pop(); if(value==this.getMin()){ stackMin.pop(); } return value; } //得到當前最小值 public int getMin() { if
(stackMin.isEmpty()){ throw new RuntimeException("Your stack is empty!"); } return stackMin.peek(); } }
/** 1.設計一個有getMin功能的棧
*   題目:實現一個特殊的棧,在實現棧的基本功能的基礎上,再實現返回棧中最小元素的操作。
*   要求:pop、push、getMin操作的時間複雜度都是O(1).
*   設計的棧型別可以使用現有的棧結構
*
*   只儲存當前最小值,空間多,但彈出時快
*/
public class MyStack2 {
    private Stack<Integer> stackData;
    private Stack<Integer> stackMin;

    public MyStack2() {
        stackData=new Stack<Integer>();
        stackMin=new Stack<Integer>();
    }

    public void push(int newNum){
        if(stackMin.isEmpty()){
            stackMin.push(newNum);
        }else if (newNum<this.getMin()) {
            stackMin.push(newNum);
        }else {
            int value =stackMin.peek();
            stackMin.push(value);
        }
        stackData.push(newNum);
    }

    public int pop(){
        if(stackData.isEmpty()){
            throw new RuntimeException("Your stack is empty!");
        }
        stackMin.pop();
        return stackData.pop();
    }

    public int getMin(){
        if(stackMin.isEmpty()){
            throw new RuntimeException("Your stack is empty!");
        }
        return stackMin.peek();
    }
}