Article directory
topic
train of thought
Stack: push() and pop() functions corresponding to the array first in last out
- The first step is to create an array for storage;
- 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.
- 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
};