原题链接:155. 最小栈
solution: 一个栈存储数据,一个占存储最小值
用系统自带stack:
class MinStack {
public:
stack<int> st,minst;
MinStack() {
}
void push(int val) {
st.push(val);
if(minst.empty() || minst.top() >= val){
minst.push(val);
}
}
void pop() {
if(minst.top() == st.top()) minst.pop();
st.pop();
}
int top() {
return st.top();
}
int getMin() {
return minst.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(val);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
手写栈:
class MinStack {
public:
int st[30010],minst[30010];
int idx1 = -1;
int idx2 = -1;
MinStack() {
}
void push(int val) {
st[++idx1] = val;
if(idx2 == -1 || minst[idx2] >= val){
minst[++idx2] = val;
}
}
void pop() {
if(st[idx1] == minst[idx2]) idx2--;
idx1--;
}
int top() {
return st[idx1];
}
int getMin() {
return minst[idx2];
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(val);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/