2015年5月19日星期二

Min Stack leetcode

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.
在维护stack同时维护一个minstack, 记录stack内最小值 当stack push新值的时候 minstack 将新值与它最上面的值比较 哪个小就新push哪个 这样ministack最顶层都是当前stack的最小值

class MinStack {
    private Stack<Integer> stack = new Stack<Integer>();
    private Stack<Integer> ministack = new Stack<Integer>();
    public void push(int x) {
       stack.push(x);
        if (ministack.empty()) {
            ministack.push(x);
        } else if (ministack.peek() < x) {
            ministack.push(ministack.peek());
        } else {
            ministack.push(x);
        } 
    }

    public void pop() {
        ministack.pop();
        stack.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return ministack.peek();
    }
}

没有评论:

发表评论