Title Description:
Define the data structure of the stack, implement a min function that can get the smallest element of the stack in the type. Ideas:
Because each time the element into the stack can not guarantee that the top element is the smallest, so need to find a way to make the top element of the stack is always the smallest element, sorting is a kind of thinking, but each sort also designed to re-stack and into the stack, think it should not be so.
One idea is that you can use a secondary stack , which is equivalent to a space-time change. The specific idea is: when the new element into the stack of the original stack top element is small, the element is placed in a secondary stack, if the new stack of elements than the original stack top element, then in the secondary stack to continue to put the smallest element. This goes on and on, when the smallest element needs to be taken, the top element of the stack is taken from the auxiliary stack, so the complexity of the time is O (1). And one of the benefits of doing this is that after the smallest element, the next small element (still the smallest) is taken. Code implementation:
import java.util.Stack;
public class Solution {stack<integer> data = new stack<integer> ();
stack<integer> assist = new stack<integer> ();
public void push (int node) {Data.push (node);
if (assist.size () = = 0 | | Node < Assist.peek ()) {Assist.push (node);
}else{Assist.push (Assist.peek ());
}} public void Pop () {if (data.size () > 0 && assist.size () >0) {Data.pop ();
Assist.pop ();
}} public int top () {if (data.size () > 0) {return data.peek ();
} return-1;
} public int min () {if (Data.size () >0 && assist.size () > 0) {return assist.peek ();
} return-1; }
}