155.最小栈

最小栈

设计一个支持 push、pop、top 操作,并能在常数时间内检索到最小元素的栈。

实现 MinStack 类:

  • MinStack() 初始化堆栈对象
  • void push(int val) 将元素 val 推入堆栈
  • void pop() 删除堆栈顶部的元素
  • int top() 获取堆栈顶部的元素
  • int getMin() 获取堆栈中的最小元素

示例:

输入:
[“MinStack”,”push”,”push”,”push”,”getMin”,”pop”,”top”,”getMin”]
[[],[-2],[0],[-3],[],[],[],[]]
输出:
[null,null,null,null,-3,null,0,-2]

提示:

  • $-2^{31}$ <= val <= $2^{31} - 1$
  • pop、top 和 getMin 操作总是在 非空栈 上调用
  • push、pop、top 和 getMin 最多被调用 $3 * 10^4$ 次

解析

使用辅助栈同步记录每个状态下的最小值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var MinStack = function () {
this.stack = [];
this.minStack = [Infinity];
};

MinStack.prototype.push = function (val) {
this.stack.push(val);
this.minStack.push(Math.min(this.minStack[this.minStack.length - 1], val));
};

MinStack.prototype.pop = function () {
this.stack.pop();
this.minStack.pop();
};

MinStack.prototype.top = function () {
return this.stack[this.stack.length - 1];
};

MinStack.prototype.getMin = function () {
return this.minStack[this.minStack.length - 1];
};

辅助栈的栈顶始终是当前栈中的最小值,所有操作均为 O(1)。


155.最小栈
https://leetcode.lz5z.com/155.min-stack/
作者
tickli
发布于
2024年5月11日
许可协议