题目描述
解题思路
- 创建两个栈,分别为
stack1
和stack2
stack1
用于存储数据,经历push
、pop
、top
,stack2
用于存储最小数字
(1)push
:向stack1
存入数字x
,如果stack2
为空或者stack2
的顶部的数字大于x
,就存入x
,否则不存
(2)pop
:删除stack1
顶部元素,此时要注意,如果stack2
的顶部数字和stack1
的顶部数字相同,那么stack2
的顶部数字也要删除
(3)top
:返回stack1
的顶部数字,注意是返回数字,但不删除,所以不能用pop
,只能索引
(4)min
:返回stack2
的顶部数字,注意是返回数字,但不删除,所以不能用pop
,只能索引
注意点
原本在python中,要访问栈【顶部】或者队列【队尾】数据,只需要-1作为索引即可,但是在js中是不行的,因为
在JS中,有负索引这一说法,所以如果我们每一指定
stack[-1]
等于什么的话,stack[-1]
就是undefined
,如果我们指定stack[-1] = 12
,就可以查询问stack[-1]
若要访问栈【顶部】或者队列【队尾】数据,只能老老实实使用stack.length-1
作为索引
代码实现
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.stack1 = [];
this.stack2 = [];
this.minValue = -1;
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.stack1.push(x);
if (!this.stack2.length || this.stack2[this.stack2.length -1] >= x) {
this.stack2.push(x)
};
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
if (this.stack2[this.stack2.length -1] === this.stack1.pop()) {
return this.stack2.pop();
}
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack1[this.stack1.length -1];
};
/**
* @return {number}
*/
MinStack.prototype.min = function() {
return this.stack2[this.stack2.length -1];
};
/**
* Your MinStack object will be instantiated and called as such:
* var obj = new MinStack()
* obj.push(x)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.min()
*/