leetcode - 155 最小栈

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

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

思路:

 使用两个栈来实现,一个栈来按顺序存储push进来的数据,另一个用来存出现过的最小值。

class MinStack {
    private Stack<Integer> stack1 = new Stack<>();//数据栈
    private Stack<Integer> stack2 = new Stack<>();//辅助栈
    /** initialize your data structure here. */
    public MinStack() {
        
    }
    
    public void push(int x) {
        stack1.push(x);
        if(stack2.isEmpty() || stack2.peek() >= x){
            stack2.push(x);
        }
    }
    
    public void pop() {
        if(stack2.peek().equals(stack1.pop())){
            stack2.pop();
        }
    }
    
    public int top() {
        return stack1.peek();
    }
    
    public int getMin() {
        return stack2.peek();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43322057/article/details/84402185