Java【力扣155】最小栈

设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-stack

代码如下:

class MinStack {
    private Stack<Integer> s1=new Stack<>();
    private Stack<Integer> s2=new Stack<>();

    public MinStack() {

    }

    public void push(int val) {
        s1.push(val);
        if(s2.isEmpty()){
            s2.push(val);
        }else {
            int temp=s2.peek();
            s2.push(Math.min(temp,val));
        }
    }

    public void pop() {
        s1.pop();
        s2.pop();
    }

    public int top() {
        return s1.peek();
    }

    public int getMin() {
        return s2.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(val);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

实现结果:

猜你喜欢

转载自blog.csdn.net/m0_62218217/article/details/122658132
今日推荐