https://leetcode-cn.com/problems/min-stack-lcci/
难度简单24收藏分享切换为英文关注反馈
请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
示例:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2.
执行用时:180 ms, 在所有 JavaScript 提交中击败了31.33%的用户
内存消耗:44.2 MB, 在所有 JavaScript 提交中击败了88.37%的用户
/**
* initialize your data structure here.
*/
var MinStack = function () {
this.arr = [];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function (x) {
this.arr.push(x);
};
/**
* @return {void}
*/
MinStack.prototype.pop = function () {
this.arr.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function () {
return this.arr[this.arr.length-1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function () {
var min = 1e18;
for (var i = 0; i < this.arr.length; i++) {
if (this.arr[i] < min) min = this.arr[i];
}
return 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()
*/