Design a stack of getMin function

Design a stack of getMin function

topic

Implement a special stack, based on the basic functions of the stack, and then return to the operation of the smallest element in the stack

Claim

1. The time complexity of pop push getMin is O(1)
2. The design stack type can use the ready-made stack structure

Ideas

Create two stack structures, stack and minStack respectively. When the stack is pushed, the stack is pushed into the stack normally, and minStack needs to judge whether the element on the top of the stack is larger than the element pushed on the stack. If it is, push the element on the stack into minStack. When the stack is popped, the stack is popped normally, and minStack needs to determine the stack element Whether it is consistent with the top element of the stack, if so, minStack also needs to be popped out of the stack. To get the smallest element in the stack, you only need to return the top element of minStack.

Code

var minStack = []
var stack= [];
function push(ele){
    
    
   stack.unshift(ele);
   if(!minStack[0]||ele<=minStack[0]){
    
    
       minStack.unshift(ele)
   }  
}
function pop(){
    
    
   let ele=stack.shift();
   if(minStack[0]&&ele==minStack[0]){
    
    
       minStack.shift()
   }
}
function getMin(){
    
    
return minStack[0]?minStack[0]:null
}

Simple test

let arr1 = [7,5,3,2,5,8,9,8,7,9,4,5,6,2,3,1,5,4,6,5,12]
for (let index = 0; index < arr1.length; index++) {
    
    
    push(arr1[index]); 
}
console.log(stack)
console.log(minStack)
for (let index = 0; index < arr1.length; index++) {
    
    
    pop(stack[index])
    console.log(`删除${
      
      index}元素:`,getMin()) 
}

Code download address

thank

If you feel helpful to your study, please share it with those who need it, or like to encourage it, thank you for your support, and
I will continue to update it. . .

Guess you like

Origin blog.csdn.net/XINpxXIN/article/details/104288648