設計一個具備getMin功能的棧

請設計一個棧,除了常規棧支持的pop與push函數之外,還支持min函數,該函數返回棧元素中的最小值。執行push、pop和min操做的時間複雜度必須爲O(1)。java

來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/min-stack-lcci
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。

網絡


import java.util.Stack;

class MinStack {

    private Stack<Integer> rawStack;

    private Stack<Integer> assistStack;

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

        this.rawStack = new Stack<>();
        this.assistStack = new Stack<>();

    }

    /**
     * 輔助棧頂維護當前最小元素
     * @param x
     */
    public void push(int x) {

        this.rawStack.push(x);

        if (this.assistStack.isEmpty() || this.assistStack.peek() >= x) {
            this.assistStack.push(x);
        }
    }

    public void pop() {

        Integer pop = this.rawStack.pop();

        if (pop.equals(this.assistStack.peek())) {
            this.assistStack.pop();
        }
    }

    public int top() {
        return this.rawStack.peek();
    }

    public int getMin() {
        return this.assistStack.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */
相關文章
相關標籤/搜索