美文网首页
155. 最小栈

155. 最小栈

作者: 梦想黑客 | 来源:发表于2020-03-03 17:31 被阅读0次

题目描述

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

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

示例:

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

解法

class MinStack {

    /** initialize your data structure here. */
    private Stack<Integer> stack;
    private int min = Integer.MAX_VALUE;
    
    public MinStack() {
        this.stack = new Stack<>();
    }
    
    public void push(int x) {
        //这里必须是<=,不然会丢失数据
        if(x <= min){
            stack.push(min);
            min = x;
        }
        stack.push(x);
    }
    
    public void pop() {
        if(stack.pop() == min){
            min = stack.pop();
        }
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return min;
    }
}

/**
 * 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-155-最小栈

    LeetCode-155-最小栈 155. 最小栈[https://leetcode-cn.com/problem...

  • 栈 问题

    155. 最小栈 常数时间内检索最小元素 使用一个辅助栈,与元素栈同步插入与删除,用于存储与每个元素对应的最小值。...

  • LeetCode:最小栈

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

  • LeetCode 155. 最小栈 | Python

    155. 最小栈 题目来源:https://leetcode-cn.com/problems/min-stack ...

  • LeetCode:155. 最小栈

    问题链接 155. 最小栈[https://leetcode-cn.com/problems/min-stack/...

  • LeetCode刷题笔记(三)栈与队列

    三. 栈与队列 python中的栈直接用list实现,队列用deque,需要导入外部包。 155. 最小栈 题目:...

  • 2.栈(二)

    题目汇总:https://leetcode-cn.com/tag/stack/155. 最小栈简单[✔]173. ...

  • LeetCodeDay24 —— 最小栈

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

  • 155. 最小栈

    155. 最小栈[https://leetcode.cn/problems/min-stack/] 设计一个支持 ...

  • 155. 最小栈

    题目地址(155. 最小栈) https://leetcode.cn/problems/min-stack/[ht...

网友评论

      本文标题:155. 最小栈

      本文链接:https://www.haomeiwen.com/subject/wqzhlhtx.html