`
hcx2013
  • 浏览: 88880 次
社区版块
存档分类
最新评论

Min Stack

 
阅读更多

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.

 

class MinStack {
	private Stack<Integer> stackData = new Stack<Integer>();
	private Stack<Integer> stackMin = new Stack<Integer>();
    public void push(int x) {
        if (stackMin.isEmpty()) {
        	stackMin.push(x);
        } else if (x <= getMin()) {
        	stackMin.push(x);
        }
        stackData.push(x);
    }

    public void pop() {
        if (stackData.isEmpty()) {
        	return;
        }
        Integer pop = stackData.pop();
        if (pop == getMin()) {
        	stackMin.pop();
        }
    }

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

    public int getMin() {
        if (stackMin.isEmpty()) {
        	return 0;
        }
        return stackMin.peek();
    }
}

 

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics