写在前面: 用了两个栈,一个栈用于存储数据,另外一个用于维护最小值,定义一个变量来监听最小值也是一样的
欢迎关注我的 力扣github仓库,有JavaScript和C++两个版本,每日更新
C++代码:
class MinStack {
public:
/** initialize your data structure here. */
stack<int> stack,flag;
MinStack() {
}
void push(int x) {
if(flag.empty() || flag.top()>=x)
flag.push(x);
stack.push(x);
}
void pop() {
if(stack.top()==flag.top())
flag.pop();
stack.pop();
}
int top() {
return stack.top();
}
int getMin() {
return flag.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
JS代码:
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.stack=[]
this.minStack=[]
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.stack.push(x);
if(this.minStack.length==0 || x<=this.minStack[this.minStack.length-1])
this.minStack.push(x);
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
if(this.stack[this.stack.length-1]==this.minStack[this.minStack.length-1])
this.minStack.pop();
this.stack.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack[this.stack.length-1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
return this.minStack[this.minStack.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.getMin()
*/