minStack

来源:互联网 发布:淘宝店头在线设计 编辑:程序博客网 时间:2024/06/06 00:32

Min Stack

 
用两个这样的栈可以实现一个再O(1)内获取最小元的队列。

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.

</pre><pre co
static class MinStack {        final static int SIZE = 100000;        int stk[] = new int[SIZE];        int top = 0;        int min = Integer.MAX_VALUE;        int nextMin[] = new int[SIZE];        public void push(int x) {            if (x <= min) {                min = x;                nextMin[top] = top;            } else {                if (top - 1 >= 0)                    nextMin[top] = nextMin[top - 1];            }            stk[top++] = x;        }        public void pop() {            --top;            if (stk[top] == min) {                if (top - 1 >= 0)                    min = stk[nextMin[top - 1]];            }            if(top==0){                min = Integer.MAX_VALUE;            }        }        public int top() {            if (top > 0) ;            return stk[top - 1];        }        public int getMin() {            return min;        }    }

0 0
原创粉丝点击