法1:两个栈实现最小栈
注意:思路比较直接!
Python
class MinStack:
def __init__(self):
self.stack1 = list()
self.stack2 = list() # min
def push(self, val: int) -> None:
self.stack1.append(val)
if len(self.stack2) == 0 or self.stack2[-1] >= val:
self.stack2.append(val)
def pop(self) -> None:
top_val = self.stack1.pop()
if top_val == self.stack2[-1]:
self.stack2.pop()
def top(self) -> int:
return self.stack1[-1]
def getMin(self) -> int:
return self.stack2[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
Java
class MinStack {
Stack<Integer> stack1;
Stack<Integer> stack2;
public MinStack() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int val) {
stack1.push(val);
if (stack2.isEmpty()) {
stack2.push(val);
} else if (val <= stack2.peek()) {
stack2.push(val);
}
}
public void pop() {
int val = stack1.pop();
if (val == stack2.peek()) { // 注意:这里需要加"=",会有多个最小元素push进来
stack2.pop();
}
}
public int top() {
return stack1.peek();
}
public int getMin() {
return stack2.peek();
}
}
本文介绍了如何通过两个栈实现一个`MinStack`类,当插入和删除元素时能快速获取当前的最小值。主要涉及`push`、`pop`、`top`和`getMin`方法的实现策略。
842

被折叠的 条评论
为什么被折叠?



