Likou quiz notes day4 (stack containing min function)

Article directory

topic

insert image description here

train of thought

Stack: push() and pop() functions corresponding to the array first in last out

  1. The first step is to create an array for storage;
  2. When we store it through push, it is stored as an object, which has two attribute children, namely val and min. Corresponds to the currently stored value and the minimum value among all currently stored values.
  3. When a new object is pushed in, min is updated.

the code

var MinStack = function() {
    
    
    this.arr=[]
};

/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
    
    
    this.arr.push({
    
    
        val:x,
        min: this.arr.length ? Math.min( x, this.min()) : x,
    })
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
    
    
    this.arr.pop()
};

/**
 * @return {number}
 */
MinStack.prototype.top = function() {
    
    
    return this.arr[this.arr.length-1].val
};

/**
 * @return {number}
 */
MinStack.prototype.min = function() {
    
    
    return this.arr[this.arr.length-1].min
};


Guess you like

Origin blog.csdn.net/weixin_51610980/article/details/128377671