1. 题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
提示:
- 各函数的调用总次数不超过 20000 次
2. 解题思路
这里我们需要保存一个最小值,所以在每次push一个新的值时,可以push一个对象。对象中包含两个属性,分别是这次push的值和当前栈中最小的值,并且要保持这个最小值是最新的,这样最后一个值push完成之后,和他一起的最小值就是当前队列中的最小值。
复杂度分析:
- 时间复杂度:O(1), push(), pop(), top(), min() 方法的时间复杂度均为常数级别;
- 空间复杂度:O(N), 这里需要一个长度为N的栈来保存每个值对应的对象。
3. 代码实现
```typescript /**- initialize your data structure here. */ var MinStack = function() { this.stack = []; };
/**
- @param {number} x
- @return {void}
*/
MinStack.prototype.push = function(x) {
this.stack.push({
}) };val: x,
min: this.stack.length ? Math.min(x, this.min()) : x,
/**
- @return {void} */ MinStack.prototype.pop = function() { this.stack.pop() };
/**
- @return {number} */ MinStack.prototype.top = function() { return this.stack[this.stack.length - 1].val; };
/**
- @return {number} */ MinStack.prototype.min = function() { return this.stack[this.stack.length - 1].min; };
/**