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.
This solution on the discuss: Https://oj.leetcode.com/discuss/15679/share-my-java-solution-with-only-one-stack is very ingenious, The key to the algorithm is to save the difference between the current element and the smallest element with a stack. To avoid integer.maxvalue-integer.minvalue this exception, use a long type to save. The Java code is as follows:
Public classMinstack {LongMin Stack<long> Stack; Public Minstack() {stack=NewStack<> (); } Public void Push(intx) {if(Stack.isempty ()) {Stack.push (0L); Min=x; }Else{Stack.push (x-min);//could is negative if min value needs to change if(x<min) min=x; } } Public void Pop() {if(Stack.isempty ())return;LongPop=stack.pop ();if(pop<0) Min=min-pop;//if negative, increase the Min value} Public int Top() {LongTop=stack.peek ();if(top>0){return(int) (top+min); }Else{return(int) (min); } } Public int Getmin() {return(int) min; }}
The time performance of this algorithm is as follows:
But I get "Memory Limit exceeded" when I implement the same algorithm in C + +, because when I use a long type, it's actually two stacks. Still, the idea of this algorithm is worth learning.
Leetcode[stack]: Min stack