Question
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.
Solution
Original thinking is-to-use-stacks, one-to-store input elements, and the other are to store current min value.
However, there is an improvement.
This stack was to store diff between input value and the current min value.
If current value < min value, we set min as current imput value.
Therefore, when we pop or peek each element in stack, we know:
If it's greater than 0, then it must is greater than current min value.
If It's smaller than 0, then it must equal to current min value.
1 classMinstack {2Stack<long>diff;3 Private Longmin;4 5 PublicMinstack () {6Min =Integer.max_value;7diff =NewStack<long>();8 }9 Public voidPushintx) {TenDiff.push ((Long) x-min); Onemin = x < min?x:min; A } - Public voidpop () { - if(Diff.size () < 1) the return; - LongTMP =Diff.pop (); - if(TMP < 0) -Min-=tmp; + } - Public intTop () { + LongTMP =Diff.peek (); A if(TMP < 0) atTMP =min; - Else -TMP + =min; - return(int) tmp; - } - Public intgetmin () { in return(int) min; - } to}
Min Stack Solution