How would you design a stack which, in addition to push and pop, also has a function
min which returns the minimum element? Push, pop and min should all operate in
O(1) time.
min which returns the minimum element? Push, pop and min should all operate in
O(1) time.
public class StackWithMin extends Stack<NodeWithMin> {
public void push(int value) {
int newMin = Math.min(value, min());
super.push(new NodeWithMin(value, newMin));
}
}
public int min() {
if (this.isEmpty()) {
return Integer.MAX_VALUE;
} else {
return peek().min;
}
}
class NodeWithMin {
public int value;
public int min;
public NodeWithMin(int v, int min){
value = v;
this.min = min;
}
}

本文介绍了一种特殊的栈结构,该栈除了基本的push和pop操作外,还额外提供了一个min函数用以返回栈内最小元素。这种特殊的数据结构在进行push、pop及min操作时均能保证O(1)的时间复杂度。通过维护每个节点的当前最小值,确保了在任何时候都能快速找到最小元素。
303

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



