包含min函数的栈
维护两个栈:栈st存储所有元素,minSt是一个单调栈,栈顶元素为min
1. 入栈:st.push(x); 若minSt.top >= x或minSt为空,x入栈minSt
2. 出栈:若minSt与st栈顶元素相同,则二者都出栈,否则st出栈
3. 获取最小值:若minSt不为空,返回minSt栈顶元素
class MinStack {
public:
stack<int> st;
stack<int> minSt;
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
st.push(x);
if(minSt.empty() || minSt.top() >= x) minSt.push(x);
}
void pop() {
if(minSt.top() == st.top()) minSt.pop();
if(!st.empty()) st.pop();
}
int top() {
if(!st.empty()) return st.top();
else return -1;
}
int getMin() {
if(!minSt.empty()) return minSt.top();
else return -1;
}
};
/**
* 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();
*/
原文地址:https://www.cnblogs.com/Trevo/p/12585116.html
时间: 2024-10-10 14:34:54