Problem Description:
To define the data structure of the stack, implement a min function in the type that can get the smallest element of the stack. In this stack, the time complexity of calling Min,push and POPs is O (1).
Idea: Add a secondary stack to store the minimum set of values
(here to pay attention to the topic does not say the stack of element types, so try to general)
Import Java.util.Stack;
public class Solution {
stack s1=new stack ();
Stack min=new stack ();
public void push (int node) {
if (Min.empty ()) {
Min.push (node);
} else{
int top= (int) min.peek ();
if (node<top) {
Min.push (node);
} else{
Min.push (top);
}
S1.push (node);
}
public void Pop () {
if (! S1.empty ()) {
s1.pop ());
Min.pop ();
}
public int Top () {return
(int) s1.peek ();
}
public int min () {
if (Min.empty ()) {return
0;
}
return (int) min.peek ();
}
}