04-01.最小棧

題目

設計一個支持 push,pop,top 操作,並能在常數時間內檢索到最小元素的棧。

push(x) -- 將元素 x 推入棧中。
pop() -- 刪除棧頂的元素。
top() -- 獲取棧頂元素。
getMin() -- 檢索棧中的最小元素。

代碼

class MinStack {

    private Stack<Integer> dataStack = new Stack<Integer>();
    private Stack<Integer> minStack = new Stack<Integer>();

    /** initialize your data structure here. */
    public MinStack() {

    }
    
    public void push(int x) {
        dataStack.push(x);
        if(!minStack.isEmpty()){
            if(getMin() <= x){
                minStack.push(getMin());
            }else{
                minStack.push(x);
            }
        }else{
            minStack.push(x);
        }
    }
    
    public void pop() {
        dataStack.pop();
        minStack.pop();
    }
    
    public int top() {
        return dataStack.peek();
    }
    
    public int getMin() {
        return minStack.peek();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章