Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
开始想麻烦了,忘用stack了,而是用vector构造栈。。。而且得到最小还构造了最小堆。。。。擦
其实完全不用。。
minStack 记录的永远是当前所有元素中最小的,pop出比最小值大的元素时,minSt 不受影响,只有把最小值pop出时,才将minSt也pop
class MinStack {
stack<int> st;
stack<int> minSt;
public:
void push(int x) {
st.push(x);
if(minSt.empty() || x <= minSt.top())
minSt.push(x);
}
void pop() {
int top = st.top();
st.pop();
if(top==minSt.top())
minSt.pop();
}
int top() {
return st.top();
}
int getMin() {
return minSt.top();
}
};