-
Notifications
You must be signed in to change notification settings - Fork 86
Open
Description
原题链接:https://leetcode-cn.com/problems/min-stack/
解题思路:
- 使用一个栈,每个元素存储一个对象或数组,其中保存当前栈的值和最小值。
- 每次有值入栈时,存储当前值,在对比之前存储的最小值与当前值的大小,取较小值存储。
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
// 如果当前栈为空,则直接存储
if (!this.stack.length) {
this.stack.push({
value: x,
min: x,
});
} else {
// 对比当前最小值,进行存储
this.stack.push({
value: x,
min: Math.min(x, this.stack[this.stack.length - 1].min),
});
}
};
/**
* @return {void}
*/
MinStack.prototype.pop = function () {
this.stack.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function () {
return this.stack[this.stack.length - 1].value;
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function () {
return this.stack[this.stack.length - 1].min;
};
Metadata
Metadata
Assignees
Labels
No labels