Achieve a minimum stack

To implement a stack, the stack having a stack (POP), push (Push), taking three smallest element method (getMin). To ensure that the time complexity of the three methods is O (1).

 

E.g:

  * Bottom of the stack -> stack
  * 4,9,7,3,8,5

 

Ideas:

  Not simply by recording the minimum value when the smallest element of the stack as the stack. Because there may be performed after the stack operation, the minimum value is pop, so that the smallest element not found.

  Right ideas: 

    1. Create a backup of the stack, the stack push each main element of time, and all the top element of the stack backup compare
    2. Main stack push element is smaller than the top element of the stack back up, while the main stack push, to push the elements are also backup stack;
    3. When the main stack pop elements, and the need to back up the stack top element, and if equal, the top element needs to be backed up can pop the stack.

 

Code:

. 1  Import of java.util.ArrayList;
 2  Import java.util.List;
 . 3  Import the java.util.Stack;
 . 4  / ** 
. 5  * to implement a stack, the stack having a stack (POP), push (Push), The method takes three smallest element (getMin).
6  * To ensure that the time complexity of the three methods is O (. 1)
 . 7  *
 . 8  * bottom of the stack -> stack
 . 9  * 4,9,7,3,8,5
 10   * / 

. 11 public class MinStack { 12 is Private Stack <Integer> = mainStack new new Stack <> (); 13 is Private Stack <Integer> = minStack new new Stack <> (); 14 15 public void push (int element){ 16 mainStack.push(element); 17 if (minStack.empty() || element <= minStack.peek()){ 18 minStack.push(element); 19 } 20 } 21 22 public Integer pop(){ 23 if (mainStack.peek().equals(minStack.peek())){ 24 minStack.pop(); 25 } 26 return mainStack.pop(); 27 } 28 29 public Integer getMinElement(){ 30 if (!minStack.isEmpty()){ 31 return minStack.peek(); 32 }else { 33 return null; 34 } 35 } 36 37 public List<Integer> getStackElement(){ 38 List<Integer> elementList = new ArrayList<>(); 39 for (int i=0; i<mainStack.size(); i++){ 40 elementList.add(mainStack.get(i)); 41 } 42 return elementList; 43 } 44 45 46 public static void main(String[] args){ 47 MinStack stack = new MinStack(); 48 stack.push(4); 49 stack.push(9); 50 stack.push(7); 51 stack.push(3); 52 stack.push(8); 53 stack.push(5); 54 System.out.println(stack.getStackElement().toString()); 55 System.out.println("The min element is: "+ stack.getMinElement()); 56 System.out.println("pop start..."); 57 stack.pop(); 58 stack.pop(); 59 stack.pop(); 60 System.out.println("pop end..."); 61 System.out.println(stack.getStackElement().toString()); 62 System.out.println("The min element is: "+ stack.getMinElement()); 63 } 64 }

 result:

[4, 9, 7, 3, 8, 5]
The min element is: 3
pop start...
pop end...
[4, 9, 7]
The min element is: 4

 

Guess you like

Origin www.cnblogs.com/zldmy/p/11486681.html
Recommended