Implement O (1) to obtain the stack with the maximum and minimum values ---- java
Implement O (1) to obtain the stack and queue with the maximum and minimum values ---- java
I. How to Implement the stack that includes the function for obtaining the minimum value
Problem: define the data structure of the stack. Implement a getMin function in this type to obtain the minimum element of the stack. In this stack, the time complexity of calling getMin, push, and pop is O (1 ).
Minimum principle: Use an auxiliary stack stack2 to remember the current minimum value of stack1 each time: add the current minimum value to stack2 when stack1 is in the stack; When stack1 is out of the stack, stack2 also generates an element of the stack. The minimum value is obtained from stack2. O (1)
Max idea: Same as O (1)
Median idea: Sorts stacks with the middle value, but the time is not O (1)
Package com. sheepmu; import java. util. Arrays; import java. util. Stack; public class SpecialStack
> {Stack
Stack1 = new Stack
(); Stack
StackMin = new Stack
(); // Store the Stack for minimum values
StackMax = new Stack
(); // Store the stack public void push (E) {stack1.push (e); if (stackMin. isEmpty () | e. compareTo (stackMin. peek () <0) stackMin. push (e); // if the minimum stack is empty, push it into stackMin at the same time; else if (e. compareTo (stackMin. peek ()> 0) stackMin. push (stackMin. peek (); if (stackMax. isEmpty () | e. compareTo (stackMin. peek ()> 0) stackMax. push (e); else if (e. compareTo (stackMax. peek () <0) stackMin. push (stackMax. peek ();} public E pop () // be sure to remember that pop is available only when it is not empty. () {If (! Stack1.isEmpty ()&&! StackMin. isEmpty ()&&! StackMax. isEmpty () {E e = stack1.pop (); stackMin. pop (); stackMax. pop (); return e;} else {System. out. println ("Stack is empty"); return null ;}} public E getMin () {return stackMin. peek ();} public E getMax () {return stackMax. peek ();} public E getMed () {E [] ss = (E []) stack1.toArray (); // stack1.toArray () returns Object [], stack -----> array Arrays. sort (ss); return ss [ss. length/2] ;}}