1
cpp
class MinStack {
stack x_stack;
stack min_stack;
public:
MinStack() {
min_stack.push(INT_MAX);
}
void push(int x) {
x_stack.push(x);
min_stack.push(::min(min_stack.top(),x));
}
void pop() {
x_stack.pop();
min_stack.pop();
}
int top() {
return x_stack.top();
}
int min() {
return min_stack.top();
}
};
python
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = [math.inf]
def push(self, x: int) -> None:
self.stack.append(x)
self.min_stack.append(min(x, self.min_stack[-1]))
def pop(self) -> None:
self.stack.pop()
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def min(self) -> int:
return self.min_stack[-1]
2
cpp
class Solution {
public:
bool validateStackSequences(vector& pushed, vector& popped) {
stack st; // 建立辅助栈
int index = 0;
for (int i = 0; i < pushed.size(); ++ i) { //依次遍历pushed中所有元素,模拟入栈操作
st.push(pushed[i]);
//如果辅助栈的栈顶元素与popped中元素相等,模拟出栈操作
while (!st.empty() && st.top() == popped[index]) {
st.pop();
index++;
}
}
return st.empty(); //判断辅助栈的状态。为空,返回true;不为空,返回false。
}
};
python
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stack, i = [], 0
for num in pushed:
stack.append(num) # num 入栈
while stack and stack[-1] == popped[i]: # 循环判断与出栈
stack.pop()
i += 1
return not stack



