数据栈 + 辅助栈:
判断数据是否加入辅助栈时:
if( min_stk.empty() || val <= min_stk.top())
1. 必须先判断 min_stk.empty() , 再或者 val <= min_stk.top()
原因: 一开始辅助栈是空的,没有min_stk.top(), 此时若先判断 val <= min_stk.top() , 将出错;
2. val <= min_stk.top() 必须是 <= 判断
原因: eg: 依次推入[0][1][0]
val <= min_stk.top() 辅助栈:[0, 0]
val < min_stk.top() 辅助栈:[0] 数据栈和辅助栈第一次弹出0后,辅助栈为空,此时再调用 getMin(), 出错
c++
class MinStack {
public:
stack<int> x_stk;
stack<int> min_stk;
MinStack() {
}
void push(int val) {
if( min_stk.empty() || val <= min_stk.top()){
min_stk.push(val);
}
x_stk.push(val);
}
void pop() {
if(min_stk.top() == x_stk.top()){
min_stk.pop();
}
x_stk.pop();
}
int top() {
return x_stk.top();
}
int getMin() {
return min_stk.top();
}
};
python
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.x_stk = []
self.min_stk = []
def push(self, val: int) -> None:
if not self.min_stk or val <= self.min_stk[-1]:
self.min_stk.append(val)
self.x_stk.append(val)
def pop(self) -> None:
if self.x_stk[-1] == self.min_stk[-1]:
self.min_stk.pop()
self.x_stk.pop()
def top(self) -> int:
return self.x_stk[-1]
def getMin(self) -> int:
return self.min_stk[-1]
一个栈 元组入栈 :
c++ 元组入栈定义 stack<pair<int, int>> st;
st.push({x, x});
python 元组入栈定义 stk = []
stk.append((x, x))
c++
class MinStack {
public:
stack<pair<int, int>> stk;
MinStack() {
}
void push(int val) {
if(stk.empty()){
stk.push({val, val});
}else{
stk.push({val, min(val, stk.top().second)});
}
}
void pop() {
stk.pop();
}
int top() {
return stk.top().first;
}
int getMin() {
return stk.top().second;
}
};
python
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stk = []
def push(self, val: int) -> None:
if not self.stk:
self.stk.append((val, val))
else:
self.stk.append((val, min(val,self.stk[-1][-1])))
def pop(self) -> None:
self.stk.pop()
def top(self) -> int:
return self.stk[-1][0]
def getMin(self) -> int:
return self.stk[-1][-1]