Implement O (1) to get the maximum minimum value of the stack and queue----java
I. how to implement a stack that includes getting the minimum function
Problem: Define the data structure of the stack, implement a getmin function that can get the smallest element of the stack in that type. In this stack, the time complexity of calling getmin, push, and Pop is O (1).
Minimum idea : Use a secondary stack stack2 to remember the current minimum value of each stack stack1: When the Stack1 is in the stack, the current minimum value is added to the Stack2, and when the stack1 element is out of the stack, the Stack2 also stacks an element. The minimum value is obtained from the Stack2 and the top element of the stack. O (1)
Max idea : Ditto O (1)
Median idea : sort the stack. Take the middle value, but the time is not O (1)
Package Com.sheepmu;import Java.util.arrays;import Java.util.stack;public class Specialstack<e extends Comparable <E>>{Stack<E> stack1=new stack<e> (); Stack<e> stackmin=new stack<e> ()///store the stack for minimum value stack<e> stackmax=new stack<e> ();// The stack public void push (e) {Stack1.push (e), where the maximum value is stored, and the IF (Stackmin.isempty () | | E.compareto (Stackmin.peek ()) <0) Stackmin.push (e);//If the minimum stack is an empty push into the stack, push it into stackmin;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 ()//Must remember. Non-null talent pop () {if (!stack1.isempty () &&!stackmin.isempty () &&!stackmax.isempty ()) {E e=stack1.pop (); Stackmin.pop (); Stackmax.pop (); return e;} Else{system.out.println ("Stack is already empty"); return null;}} Public E Getmin () {return Stackmin.peek ();} Public E Getmax () {return Stackmax.peek ();} Public E getmed () {e[] Ss=stack1.toarray (nEW e[stack.size ()]);//stack1.toarray () returns object[], stack-----> array; cannot toArray and cast again. Will error Arrays.sort (SS); return SS[SS.LENGTH/2];} }
Implement O (1) to get the maximum minimum value of the stack----Java