leetcode 算法题155 (简单036) 最小栈
- 题目介绍
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) -- 将元素 x 推入栈中。
pop() -- 删除栈顶的元素。
top() -- 获取栈顶元素。
getMin() -- 检索栈中的最小元素。
- 示例
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop() minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2.
- 解法一
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.stack = [];
this.min = null;
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.stack[this.stack.length] = x;
if (this.min === null) {
this.min = x;
} else {
this.min = Math.min(this.min, x);
}
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
if (this.stack.length) {
let x = this.stack[this.stack.length - 1];
this.stack.length = this.stack.length - 1;
if (x === this.min) {
this.setMin();
}
}
return null;
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
if (this.stack.length) {
return this.stack[this.stack.length - 1];
}
return null;
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
return this.min;
};
MinStack.prototype.setMin = function() {
let stack = this.stack;
if (!stack.length) {
this.min = null;
return;
}
let min = stack[0], i = 1;
while (i < stack.length) {
min = Math.min(min, stack[i++]);
}
this.min = min;
};
/**
* 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.getMin()
*/
执行用时 : 144ms, 在所有 JavaScript 提交中击败了95.68%的用户
内存消耗 : 44.3MB, 在所有 JavaScript 提交中击败了32.31%的用户
- 解法一
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.stack = [];
this.min = null;
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.stack.push(x);
if (this.min === null) {
this.min = x;
} else {
this.min = Math.min(this.min, x);
}
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
if (this.stack.length) {
let x = this.stack.pop();
if (x === this.min) {
this.setMin();
}
}
return null;
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
if (this.stack.length) {
return this.stack[this.stack.length - 1];
}
return null;
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
return this.min;
};
MinStack.prototype.setMin = function() {
let stack = this.stack;
if (!stack.length) {
this.min = null;
return;
}
let min = stack[0], i = 1;
while (i < stack.length) {
min = Math.min(min, stack[i++]);
}
this.min = min;
};
/**
* 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.getMin()
*/
执行用时 : 160ms, 在所有 JavaScript 提交中击败了75.30%的用户
内存消耗 : 44.3MB, 在所有 JavaScript 提交中击败了35.04%的用户