题目链接
思路分析
题目中明确要求push, pop, min的时间复杂度是O(1),如果我们仅使用一个栈的话,在求解min 的时候无法满足该要求,因此需要使用另一个辅助栈来帮助我们进行求解
因此我们需要两个栈,一个用来正常存储数据,另一个min_st用来存储最小值,当入栈数据x<=min_st.top时,将x添加到min_st中,在出栈的时候,检查栈顶元素x是否和min_st栈顶元素相同,如果相同也进行出栈。
代码实现
class MinStack {
public:
/** initialize your data structure here. */
stack<int> st;
stack<int> min_st;
MinStack() {
}
void push(int x) {
st.push(x);
if(min_st.empty())
min_st.push(x);
else
{
if(min_st.top() >= x)
min_st.push(x);
}
}
void pop() {
int x = st.top();
st.pop();
if(x == min_st.top())
min_st.pop();
}
int top() {
return st.top();
}
int min() {
return min_st.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->min();
*/