美文网首页
2018-11-24 最小栈

2018-11-24 最小栈

作者: 天际神游 | 来源:发表于2018-11-24 10:17 被阅读0次

题目:

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

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

解法:

维持两个栈, 一个是正常的栈, 一个栈的栈顶是正常栈的最小元素.
在每次压入栈的时候, 保持栈顶元素是最小的, 然后入栈即可.

class MinStack {
    
    private Stack<Integer> stack;
    private Stack<Integer> mStack;
    private int length = 0;
    
    /** initialize your data structure here. */
    public MinStack() {
        stack = new Stack<>();
        mStack = new Stack<>();
    }
    
    public void push(int x) {
        stack.push(x);
        if(length == 0){
            mStack.push(x);
        }else{
            // 压入栈的时候保证当前栈顶元素是最小的
            mStack.push(Math.min(mStack.peek(), x));
        }
        length += 1;
    }
    
    public void pop() {
        length -= 1;
        mStack.pop();
        stack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return mStack.peek();
    }
}

相关文章

  • 2018-11-24 最小栈

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

  • LeetCode-155-最小栈

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

  • 最小栈

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

  • 最小栈

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

  • 最小栈

    https://leetcode-cn.com/explore/interview/card/bytedance/...

  • 最小栈

    题目描述 https://leetcode-cn.com/problems/min-stack/ 解 思路 用一个...

  • 最小栈

    题目 难度级别:简单 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。 pu...

  • 最小栈

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

  • 最小栈

    题目:MinStack minStack = new MinStack();minStack.push(-2);m...

  • 最小栈

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

网友评论

      本文标题:2018-11-24 最小栈

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