gold-3-2


请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.

//leetcode submit region begin(Prohibit modification and deletion)
class MinStack {
    List<Integer> stakList;
    int minIndex;

    /** initialize your data structure here. */
    public MinStack() {
        this.stakList = new ArrayList<>();
        this.minIndex = -1;
    }

    public void push(int x) {
        this.stakList.add(x);
        if (this.minIndex == -1) {
            this.minIndex = 0;
        } else if (x < stakList.get(this.minIndex)) {
            this.minIndex = this.stakList.size() - 1;
        }
    }

    public void pop() {
        if (!this.stakList.isEmpty()) {
            this.stakList.remove(this.stakList.size() - 1);

            if (this.minIndex == this.stakList.size()) {
                this.minIndex = -1;
                int minV = Integer.MAX_VALUE;

                for (int i = 0; i < this.stakList.size(); i++) {
                    if (this.stakList.get(i) <= minV) {
                        this.minIndex = i;
                        minV = this.stakList.get(i);
                    }
                }
            }
        }
    }

    public int top() {
        if (stakList.isEmpty()) {
            return -1;
        }
        return this.stakList.get(this.stakList.size() - 1);
    }

    public int getMin() {
        if (stakList.isEmpty()) {
            return -1;
        }
        return this.stakList.get(this.minIndex);
    }
}
/**
 * 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();
 */
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !