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 is the key to the problem is that the time complexity of getmin is constant. The simplest idea is the following:
Class Minstack {
linkedlist<integer> stack = new linkedlist<> ();
Integer min = integer.max_value;
public void push (int x) {
stack.push (x);
if (x < min) {
min = x;
}
}
public void Pop () {
stack.pop ();
min = Integer.max_value;
for (Integer index:stack) {
if (Index < min) {
min = index;
}
}
}
public int Top () {
return Stack.peek ();
}
public int getmin () {
return min;
}
}
Each time in the push and pop to find the maximum value, it is obvious that the process of pop is more complex, need to traverse the entire stack, the direct timeout. After the brainwave, each time in the push, in a stack to put the current minimum value also push in, the following code:
linkedlist<integer> stack = new linkedlist<integer> ();
linkedlist<integer> minstack = new linkedlist<integer> ();
int min = integer.max_value;
public void push (int x) {
stack.push (x);
Minstack.push (min);
}
public void Pop () {
stack.pop ();
Minstack.pop ();
}
public int Top () {
return Stack.peek ();
}
public int getmin () {
return Minstack.peek ();
}
Results Direct memory explosion, it can be imagined that each push, will simultaneously push the minimum value, equivalent to the stack of space is twice times the previous. But the optimization can be done, not push two times, but when the minimum value changes in the push. This will save a lot of space. On the Code
Class Minstack {
linkedlist<integer> stack = new linkedlist<integer> ();
linkedlist<integer> minstack = new linkedlist<integer> ();
int min = integer.max_value;
public void push (int x) {
stack.push (x);
if (min >= x) {
min = x;
Minstack.push (min);
}
}
public void Pop () {
if (min = = Stack.peek ()) {
minstack.pop ();
if (Minstack.isempty ()) {
min = integer.max_value;
} else {
min = Minstack.peek ();
}
}
Stack.pop ();
}
public int Top () {
return Stack.peek ();
}
public int getmin () {
return min;
}
}
Finally AC. But the problem can be further explored, why the storage, not the difference between the stack store it. On the code:
linkedlist<long> stack = new linkedlist<> ();
Long min = Integer.max_value;
public void push (int x) {
if (Stack.isempty ()) {
stack.push (0L);
min = x;
} else {
Stack.push (x-min);
if (x < min) {
min = x;
}
}
}
public void Pop () {
long pop = Stack.pop ();
if (Pop < 0) {
min-= pop;
}
}
public int Top () {
Long top = Stack.peek ();
if (Top > 0) {
return (int) (top+min);
} else {
return (int) min;
}
}
public int getmin () {
return (int) min;
}
The most efficient way to run ...