思路:实现这个栈的 push 和 pop 以及 top 方法都比较简单,时间复杂度都为 O(1),而难点在于实现 min 函数,最开始想到的是遍历整个栈,但时间复杂度为O(N),故不符合,因此这里需要一个时刻更新栈内最小元素的辅助栈,每次只需要获取栈顶元素便输出 min ,时间复杂度也为O(1) (看了大佬的解析才知道大佬有多细)
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.res_stack=[] // 这是主栈
this.min_stack=[Infinity] // 这是辅助栈
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.res_stack.push(x) // 主栈 push 元素
this.min_stack.push(Math.min(this.min_stack[this.min_stack.length-1],x)) // 辅助栈比较此时主栈插入的元素与辅助栈栈顶元素的大小,最后插入的是,此时主栈中最小的元素
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
this.res_stack.pop() // 主栈 pop 元素
this.min_stack.pop() // 辅助栈 将栈顶元素 pop 出去,是因为辅助栈每一个元素与主栈的 top 息息相关,故 pop 出去后,此时的辅助栈的栈顶为上一个元素进来后,主栈最小的数。
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.res_stack[this.res_stack.length-1] // 直接返回主栈栈顶
};
/**
* @return {number}
*/
MinStack.prototype.min = function() {
return this.min_stack[this.min_stack.length-1] // 直接返回辅助栈栈顶,时间复杂度很明显 O(1) !!!!
};
/**
* Your MinStack object will be instantiated and called as such:
* var obj = new MinStack()
* obj.push(x)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.min()
*/