仅使用 PUSH 和 PUSH 查找堆栈中最大的数字POP操作
谁能帮我解决这个问题的算法(这是一个面试问题):
给你一个堆栈。设计一个算法来找到最大数量 仅使用 PUSH/POP 操作。
Can anyone please help me with the Algorithm for this problem (its an Interview Question):
You are given a stack. Devise an algorithm to find the maximum number
using PUSH/POP Operations only.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
鉴于原始帖子中缺乏约束,您可以弹出所有数据并计算运行最大值:
编辑(新限制是原始堆栈不变,并且第二个可用堆栈的新资源):
Given the lack of constraints in the original post, you can just pop off all the data and compute a running maximum:
Edit (with the new restriction that the original stack is unchanged and the new resource of a second available stack):
因为原始堆栈不能是只读的(
Pop
,访问数据的唯一方式,也会修改堆栈),我们必须考虑“堆栈应该不变”的限制意味着我们必须完成后将其恢复到原始状态。我们可以通过使用 Raymond Hettinger 提出的方法中的另一个堆栈来实现:
Because original stack cannot be read-only (
Pop
, the only way to access the data, also modifies the stack), we have to consider that "the stack should be unchanged" restriction means that we have to restore it to its original state after we finish.We can do it by using another stack in method proposed by Raymond Hettinger:
有两种方法可以解决这个问题,要么你可以创建一个函数
get_max
来给出堆栈中的最大数字,或者你可以维护一些额外的信息,使用它可以给出堆栈中的最大数字在O(1)
操作中,但以额外空间
为代价。我会给你后一种解决方案。您需要做的是拥有一个额外的堆栈,对于堆栈的任何配置,该堆栈的最大元素都位于顶部。
max_stack
中弹出最上面的数字max
值时,只需从max_stack
中选择堆栈顶部。这样你就可以在
O(1)
时间内获得最大数量,并且push和pop操作也保持O(1)
。我本可以给你代码,但里面没有太多内容,因为它很简单。例如,如果您按5 - 2 - 6 - 8 - 1
的顺序推送以下数字,
max_stack
将包含5 - 5 - 6 - 8 - 8
code>,当您
弹出
数字时,当前max
将位于顶部。我希望解决方案是明确的。
There are two ways of tackling this problem, either you can make a function
get_max
which gives the maximum number in the stack, or you can maintain some extra information using which you can give the maximum number in the stack inO(1)
operation but at the cost ofextra space
. I will give you the latter solution.What you need to do is to have an
extra stack
that will have the maximum element of the stack at the top, for any configuration of the stack.max_stack
, compare the current value with the top of max_stack and push the greater one onto it.max_stack
max
value just pick the stack top frommax_stack
.This way you can get the max number in
O(1)
time and the push and pop operations also remainO(1)
. I could have give you the code but there is nothing much in it, as it is straight forward. For example if you push following numbers in the order5 - 2 - 6 - 8 - 1
max_stack
will contain5 - 5 - 6 - 8 - 8
and as you
pop
of the numbers the currentmax
will be at the top.I hope the solution is clear.