美文网首页
LeetCode T155-最小栈问题

LeetCode T155-最小栈问题

作者: 枫叶忆 | 来源:发表于2019-04-17 19:58 被阅读0次

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

    push(x) -- 将元素 x 推入栈中。

    pop() -- 删除栈顶的元素。

    top() -- 获取栈顶元素。

    getMin() -- 检索栈中的最小元素。

    解题思路:创建两个栈,一个负责不断存数据,一个只负责存最小的值(栈顶值最小)

    class MinStack {

        Stack<Integer> data;

        Stack<Integer> minStack;

        /** initialize your data structure here. */

        public MinStack() {

            data = new Stack<Integer>();

            minStack = new Stack<Integer>();

        }

    //核心代码

        public void push(int x) {

            data.push(x);

            if(minStack.empty()){

                minStack.push(x);

            }else{

                //当x大于最小栈栈顶元素时,将最小值赋给x,并push到最小栈中

                if(minStack.peek() < x){

                    x = minStack.peek();

                }

                minStack.push(x);

            }

        }

        public void pop() {

            data.pop();

            minStack.pop();

        }

        public int top() {

            return data.peek();

        }

        public int getMin() {

            return minStack.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.getMin();

    */

    相关文章

      网友评论

          本文标题:LeetCode T155-最小栈问题

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