其他分享
首页 > 其他分享> > Day1:剑指 Offer 30. 包含min函数的栈

Day1:剑指 Offer 30. 包含min函数的栈

作者:互联网

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

class MinStack {
    //stack1负责添加元素,stack2负责维护当前最小的元素
    Deque<Integer> stack1;
    Deque<Integer> stack2;
    
    /** initialize your data structure here. */
    public MinStack() {
        stack1 = new LinkedList<>();
        stack2 = new LinkedList<>();
    }
    
    public void push(int x) {
        stack1.push(x);
        if(stack2.isEmpty()){
            stack2.push(x);
        }else{
            int temp = stack2.peek();
            stack2.push(temp > x ? x : temp);
        }
    }
    
    public void pop() {
        stack1.pop();
        stack2.pop();
    }
    
    public int top() {
        return stack1.peek();
    }
    
    public int min() {
        return stack2.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.min();
 */

标签:Offer,int,30,pop,Day1,push,stack2,public,stack1
来源: https://blog.csdn.net/upset_poor/article/details/121768981