Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Your MinStack object will be instantiated and called as such:
注意考虑记录指针index永远指向当前元素/下一元素
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if(s.empty())mini[++index]=x;
else mini[++index]=min(mini[index],x);
s.push(x);
}
void pop() {
index--;
s.pop();
}
int top() {
return s.top();
}
int getMin() {
return mini[index];
}
private:
stack<int> s;
int mini[50000];
int index=-1;
};
原文:https://www.cnblogs.com/chanceYu/p/12879700.html