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
The key to this problem is how you save the numbers. In fact stack itself can be, but need to consider a problem: Join me push1,3,5,4,0, When the pop finishes 0 you need to go back to let min equals 1. So we should first push1 in the Push0, then Push0, so pop0, we pop0 before the 1 to the Min is good ~~~~~~
Import java.util.arraylist;import java.util.stack;class minstack {stack<integer> Stack = new Stack<Integer > (); int min;public static void main (String args[]) {minstack ms = new Minstack (); Ms.push (0); Ms.push (1); Ms.push (0 ); System.out.println (Ms.getmin ()); Ms.pop ();//system.out.println (Ms.pop ();); System.out.println (Ms.getmin ());} public void push (int x) { if (stack.empty () | | | X<=min) { stack.push (min); Stack.push (x); min = x; } else Stack.push (x); } public void Pop () { int tmp = Stack.pop (); if (tmp==min) Min=stack.pop (); } public int Top () { return Stack.peek (); } public int getmin () { return min; }}
"Leetcode" Min Stack