剑指 Offer 30. 包含min函数的栈(99.97%,90.87%)

话不多说,先上题目

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。

示例:

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

来源:力扣(LeetCode)

class MinStack {
    static class Node {
        private int val;
        private int minIndex;
        public Node() {}
        public Node(int val, int minIndex) {
            this.val = val;
            this.minIndex = minIndex;
        }
    }

    private Node[] arr;
    private int topIndex;

    public MinStack() {
        arr = new Node[10];
        topIndex = -1;
    }

    public void push(int x) {
        Node node = new Node();
        node.val = x;
        if (topIndex == -1) {
            node.minIndex = 0;
        } else if (x < arr[arr[topIndex].minIndex].val) {
            node.minIndex = topIndex+1;
        } else {
            node.minIndex = arr[topIndex].minIndex;
        }
        arr[++topIndex] = node;
        if (topIndex == arr.length-1) {
            resize();
        }
    }

    public void pop() {
        topIndex--;
    }

    public int top() {
        return arr[topIndex].val;
    }

    public int min() {
        return arr[arr[topIndex].minIndex].val;
    }

    private void resize() {
        int length = arr.length;
        Node[] newarr = new Node[length * 2];
        System.arraycopy(arr, 0, newarr, 0, length);
        arr = newarr;
    }
}

/**
 * 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.min();
 */

image

posted @ 2021-08-12 14:16  超级鲨鱼辣椒  阅读(34)  评论(0编辑  收藏  举报