从堆栈最小值堆栈、最小值

2023-09-11 22:55:43 作者:瑾色ら殘年

我有一个堆栈,其中包含一些整型数据。我想了解从堆栈的最小值为O(1)时间。你知道吗?

I have a stack which contains some integer data. I want to find out the min value from Stack in O(1) time. Any idea?

PS:有没有订货数据的堆栈(增加/减少)

PS: There is no ordering (increasing/decreasing) of data in Stack.

谢谢

纳文

推荐答案

使用两个堆栈。一个是数据,一个是最低要求。当你推到数据栈,推新最低到最低栈(新的最小是你推项目的分,无论是目前的最低的栈顶),而当你弹出,弹出关闭两个堆栈的(使得两个堆栈始终具有相同的元素数)。要找到的最小元素,只看最低堆栈的顶部。

Use two stacks. One is the data, one is the minimums. When you push onto the data stack, push the new minimum onto the minimums stack (the new minimum is the min of the item you're pushing and whatever is currently on the top of the minimums stack), and when you pop, pop off of both stacks (so that the two stacks always have the same number of elements). To find the minimum element, just look at the top of the minimums stack.

推,弹出并找到最小值为O(1)。

Pushing, popping and finding the min value are O(1).