我知道如何使用存储最大值的辅助堆栈为堆栈中的最大元素执行此操作。想知道这是否可以延长以在恒定时间内返回最大和最大最大值。
答案 0 :(得分:1)
不是推动辅助堆栈上的最大元素,而是放置(maximum,second_largest)对。或者你可以把它们推到两个平行的堆栈上。
伪代码:
int largest = second_largest = MIN_INT;
push(int x)
{
stack1.push(x);
stack2.push(largest);
stack3.push(second_largest);
if (x >= largest)
{
second_largest = largest;
largest = x;
}
else if (x > second_largest)
{
second_largest = x;
}
}
int pop()
{
second_largest = stack3.pop();
largest = stack2.pop();
return stack1.pop();
}
模式是撤消堆栈。每当push()
对您要跟踪的内容进行更改时,您就会在获得pop()
时保存足够的信息以撤消这些更改。
答案 1 :(得分:0)
您可以为第二个最大值创建第二个辅助堆栈。以下是插入一些数字后最小和第二最小辅助堆栈想法的示例:
Actual Stack
16 <--- top
15
29
19
18
Auxiliary Stack
15 <---- top
15
18
18
18
Second Auxiliary Stack
18 <---- top
18
N/A
N/A
N/A
我担心在具有O(1)时间复杂度的辅助堆栈的情况下,没有其他解决方案可以获得第二个最大值。
EDIT - explenation
putting i:
- put i to main stack
- if i is smaller than top of 1st auxiliary stack, put it there, if it is not
put the same number.
- if top of 1st auxiliary stack changed, put previous 1st auxiliary top to 2nd
auxiliary stack. If it is not just put the same number as it was to the top.
popping is just popping from each stack.