[JavaScript 刷题] 栈 - 最小栈, leetcode 155
github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。
题目地址:155. Min Stack
题目
如下:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the
MinStack
class:
MinStack()
initializes the stack object.void push(int val)
pushes the element val onto the stack.void pop()
removes the element on the top of the stack.int top()
gets the top element of the stack.int getMin()
retrieves the minimum element in the stack.You must implement a solution with
O(1)
time complexity for each function.
解题思路
是一道设计题,主要难点卡在了 O(1)
的时间复杂度,这里的解决方案是使用双 stack 去解决。
原本的 stack 用来保存当前值,另一个 stack 用来保存当前最小值。
如题目中给的一个案例是:[-2, 0, -3]
,正常栈进行正常存储,保存当前最小的值的 minStack
比较被加进来的值与 minStack
中最后加进的元素,随后保存较小值即可。
大致情况如下:
stack | minStack |
---|---|
-3 | -3 |
0 | -2 |
-2 | -2 |
使用 JavaScript 解题
var MinStack = function () {
this.stack = [];
this.minStack = [];
};
/**
* @param {number} val
* @return {void}
*/
MinStack.prototype.push = function (val) {
if (val < this.min) min = val;
this.stack.push(val);
const minStackPeek = this.minStack[this.minStack.length - 1];
this.minStack.push(minStackPeek < val ? minStackPeek : val);
};
/**
* @return {void}
*/
MinStack.prototype.pop = function () {
this.minStack.pop();
return this.stack.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];
};