首页 > 代码库 > CTCI 3.2
CTCI 3.2
How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.
A quite classical problem. We could use an additional stack to store the information about the minimum element. Whenever push an element, we compare it with the top of the additional stack, if the element is small or equal, push it in, or do noting. When pop an element, if it is equal to the top of the stack, then pop the top of the stack, too. In this way, we would maintain a seqence of minimum element corresponding to the pushed in elements. At any time of push, the top of the stack would always be the smallest elements which is now available.
/* Use an additional stack to store the minimum element corresponding to the sequence of elements pushed in.Whenever an element is pushed, compare it with the element on top of the stack, if it is smaller than the top, push it in, or do noting. When pop an element, compare it with the top, too. If equal, pop it from the stack.Thus the stack would maintain the minimum element before it is poped.*/public class MinStack { int stackSize; int[] stack; int[] minStack; int top = -1, mintop = -1; public MinStack(int size) { stackSize = size; stack = new int[size]; minStack = new int[size]; } public void push (int key) throws Exception { if(top + 1 >= stackSize) { throw new Exception("Out of Memory"); } top++; stack[top] = key; if(mintop == -1 || key <= minStack[mintop]) { mintop++; minStack[mintop] = key; } } public int pop() throws Exception { if(top == -1) { throw new Exception("No Element"); } int key = stack[top]; top--; if(key == minStack[mintop]) mintop--; return key; } public int min() throws Exception { if(mintop == -1) { throw new Exception("No Element"); } return minStack[mintop]; } public static void main(String[] args) { MinStack ms = new MinStack(100); try { ms.push(1); System.out.println("The minimun element is: " + ms.min()); ms.push(0); ms.push(1); System.out.println("The poped element is: " + ms.pop()); System.out.println("The minimun element is: " + ms.min()); System.out.println("The poped element is: " + ms.pop()); System.out.println("The minimun element is: " + ms.min()); } catch(Exception e) { System.out.println(e.toString()); } }}