题链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/
题描述:
解题思路:
栈 A 用于正常存储所有元素,栈 B 用于存储最小元素。
push():
(1)将 x 压入 A
(2)如果 B 为空或者 B 的栈顶元素大于等于 x 则将 x 压入 B
pop():
(1)移除 A 的栈顶元素
(2)如果该元素等于 B 的栈顶元素,则移除 B 的栈顶元素
top():
(1)返回 A 的栈顶元素
min():
(1)返回 B 的栈顶元素
代码实现
var MinStack = function() {
this.a = [];
this.b = [];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
if (this.b.length == 0) {
this.b.push(x);
} else {
let t = this.b.pop();
this.b.push(t);
if (t >= x) {
this.b.push(x);
}
}
this.a.push(x);
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
let t = this.b.pop();
if (this.a.pop() != t) {
this.b.push(t);
}
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
let t = this.a.pop();
this.a.push(t);
return t;
};
/**
* @return {number}
*/
MinStack.prototype.min = function() {
let t = this.b.pop();
this.b.push(t);
return t;
};
时间复杂度:O(1)
空间复杂度:O(n)