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.
Thinking Analysis: The main study of the use of the stack, the only tricky is how to get the minimum value in constant time, we can consider using two stacks, a stack seqstack to maintain the order of the stack, operations with the normal stack, the other minstack stack for maintaining the minimum value, When there is a smaller or equal number than the top element of the stack, the stack is placed so that the top element is always the minimum value. This way the Getmin function simply takes the top element of the stack that maintains the minimum value. An error-prone place is to delete elements in addition to removing the top element from the Seqstack, but also need to check from the top of the Minstack stack, if the deletion is just the smallest element, should be the top of the Minstack stack is also deleted. AC Code
Class Minstack { stack<integer> seqstack = new stack<integer> (); stack<integer> minstack = new stack<integer> (); public void push (int x) { int curmin; if (Minstack.isempty ()) { curmin = integer.max_value; } else{ curmin = Minstack.peek (); } if (x <= curmin) Minstack.push (x); Seqstack.push (x); } public void Pop () { if (Seqstack.isempty ()) return; else { int removedvalue = Seqstack.pop (); if (Removedvalue = = Minstack.peek ()) { minstack.pop ();}} } public int Top () { return Seqstack.peek (); } public int getmin () { return Minstack.peek (); }}
Leetcode Min Stack