首页 > 其他 > 详细

LeetCode Min Stack

时间:2015-03-09 12:52:12      阅读:228      评论:0      收藏:0      [点我收藏+]

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.
思路分析:这题主要考察栈的使用,唯一tricky的地方是如何在常数时间内得到最小值,我们可以考虑使用两个栈,一个栈seqStack用于维护入栈的顺序,操作同普通的栈,另一个minStack栈用于维护最小值,当出现比栈顶元素更小或者相等的数的时候,要入栈,使得栈顶元素总是最小值。这样getMin函数只要取维护最小值栈的栈顶元素即可。有一个容易出错的地方是删除元素的时候除了从seqStack里面删除栈顶元素之外,还需要从minStack的栈顶做检查,如果删除的刚好是最小元素,应该把minStack的栈顶也删除。
AC Code
class MinStack {
    Stack<Integer> seqStack = new Stack<Integer>();
    Stack<Integer> minStack = new Stack<Integer>();
    public void push(int x) {
        int curMin;
        if(minStack.isEmpty()){
            curMin = Integer.MAX_VALUE;
        } else{
            curMin = minStack.peek();
        }
        if(x <= curMin) minStack.push(x);
        seqStack.push(x);
    }

    public void pop() {
        if(seqStack.isEmpty()) return;
        else {
            int removedValue = seqStack.pop();
            if(removedValue == minStack.peek()){
                minStack.pop();
            }
          }
    }

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

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


LeetCode Min Stack

原文:http://blog.csdn.net/yangliuy/article/details/44152799

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!