implement a stack which not only has push, pop, but also is able to return the minimum value within O(1) time.
public class NewStack extends Stack<Node> { public void push(Node node) { if (node.getValue() < this.min()) { node.setMin(node.getValue()); } super.push(node); } public Node pop() { return super.pop(); } public int min() { if (peek() == null) { return MAX_INT; } else { peek().getMin(); } } } class Node { int value; int min; public int getValue() { return value; } public void setValue(int value) { this.value = value; } public int getMin() { return min; } public void setMin(int min) { this.min = min; } }in the previous approach, the main drawback is that in each node, they have to store the min value, it costs too many spaces. As the minimum value may stay the same if no larger element appears, so we can improve the algorithm above by removing duplicated min values. public class StackWithMin { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int value) { if (value <= min()) { stack2.push(value); } stack1.push(value); } public int pop() { if (stack1.peek() == stack2.peek() ) { stack2.pop(); } return stack1.pop(); } public int min() { if (stack2.peek() == null) { return MAX_INT; } else { return stack2.peek(); } } }
本文介绍了一种改进的栈实现方法,不仅支持基本的 push 和 pop 操作,还能在 O(1) 时间内返回最小元素值。通过在每个节点中仅存储实际值和最小值,减少了内存占用,提高了效率。
1403

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



