题目描述
blablabla
样例
blablabla
算法1
(直接用数组建立栈)
时间复杂度分析:O(1)
C++ 代码
class MinStack {
public:
/** initialize your data structure here. */
int topp=0,top_min=0;
int stack[10000],stack_min[10000];//建立两个栈,一个用于储存值,一个用于贮存每一个时刻的最小值
MinStack() {
}
void push(int x) {
stack[++topp]=x;
if(top_min==0||stack_min[top_min]>x)
stack_min[++top_min]=x;
else stack_min[++top_min]=stack_min[top_min-1];
}
void pop() {
topp--;
top_min--;
}
int top() {
return stack[topp];
}
int getMin() {
return stack_min[top_min];
}
};
/**
* 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();
*/