1. 问题描述
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
2. 解题思路
- 用数组表示栈,新建一个辅助栈用来存储最小值
- 当栈stack进行入栈操作时,最小栈的栈顶元素与入栈值进行比较,若入栈值val小,则push到最小栈,栈stack出栈,最小栈minStack也跟着出栈,由此,最小栈就时刻保持着stack中每个元素哪个状态时刻的最小值。
- 最小栈minStack无论何时栈顶元素都是此刻stack中的最小值
3. 解题
var MinStack = function() {
this.stack = [];
this.minStack = [];
};
/**
* @param {number} val
* @return {void}
*/
MinStack.prototype.push = function(val) {
this.stack.push(val);
if(!this.minStack.length) {
this.minStack.push(val);
} else {
this.minStack.push(Math.min(this.minStack[this.minStack.length - 1] , val));
}
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
this.stack.pop();
this.minStack.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack[this.stack.length - 1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
return this.minStack[this.minStack.length - 1];
};
(1) 输出:
问题来源:力扣(LeetCode)
链接: https://leetcode-cn.com/problems/min-stack/submissions/