Min Stack

来源:互联网 发布:返利网如何解绑淘宝号 编辑:程序博客网 时间:2024/05/16 09:53

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.

Show Tags
Have you met this question in a real interview? 
Yes
 
No

剑指offerP132的第21题,分析思路那里讲的很清楚,即利用额外的一个minStack来保存当前stack的最小值(在数据每次入栈的时候完成这一工作)。

代码如下:

class MinStack {    private Stack<Integer> stack = new Stack<Integer>();    //minStack用来记录当前时刻stack栈中的最小元素    private Stack<Integer> minStack = new Stack<Integer>();    public void push(int x) {        stack.push(x);        if(minStack.empty()){            minStack.push(x);        }else if(minStack.peek()<=x){            minStack.push(minStack.peek());        }else{            minStack.push(x);        }                    }    public void pop() {       stack.pop();       minStack.pop();    }    public int top() {        return stack.peek();    }    public int getMin() {        return minStack.peek();    }}



0 0
原创粉丝点击