解题思路:用java写的话有个需要注意的地方就是由于Stack中的元素用了泛型,而泛型不支持基本类型,所以需要基本类型的包装类。而包装类不同于基本类型的是包装类是引用,要比较相等不能简单使用==,要使用equals方法。
LeetCode官网unlock的提示:
Hints:
Consider space-time tradeoff. How would you keep track of the minimums using extra space?
Make sure to consider duplicate elements.
O(n) runtime, O(n) space – Extra stack:
Use an extra stack to keep track of the current minimum value. During the push operation we choose the new element or the current minimum, whichever that is smaller to push onto the min stack.
O(n) runtime, O(n) space – Minor space optimization:
If a new element is larger than the current minimum, we do not need to push it on to the min stack. When we perform the pop operation, check if the popped element is the same as the current minimum. If it is, pop it off the min stack too.
class MinStack {
private Stack<Integer> stack = new Stack<>();
private Stack<Integer> minStack = new Stack<>();
public void push(int x) {
if(minStack.isEmpty() || x <= minStack.peek())
minStack.push(x);
stack.push(x);
}
public void pop() {
if(stack.peek().equals(minStack.peek()))
minStack.pop();
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
本文介绍了一种使用两个栈来实现在O(1)时间内获取最小元素的数据结构。通过一个主栈存储所有元素,并使用另一个辅助栈跟踪当前最小值。这种方法确保了在插入、删除和查询最小值操作上都能达到O(n)的时间复杂度。
340

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



