通过使用另一个堆栈查找堆栈中的最大值

Finding the maximum value in a stack by using another stack?

本文关键字:堆栈 查找 最大值 另一个      更新时间:2023-10-16

我有下面的代码来查找堆栈中的最大值。它正在工作,但我是否应该使用另一种方法来查找最大值,因为在调用getMax()函数后,我无法显示堆栈a。

int Sorter:: getMax(){
    c.push(a.top());
    a.pop();
    while(!a.empty()){
            if(a.top() > c.top()){
            c.pop();
                    c.push(a.top());
                    a.pop();
            }
            else
                    a.pop();
    }
    return c.top();
}

保留边变量的最大值:

int max = a.top();
while(!a.empty()){
  c.push(a.top());
  a.pop()
  if(c.top() > max){
    max = c.top(); // find the maximum among the values of a.
  }
}
// This loop can be replaced with a.swap(c). As jogojapan mentioned.
// It is to demonstrate the principal.
while(!c.empty())
{
  a.push(c.top());  // return the values back into a
  c.pop();
}
return max;

O(1)查找堆栈最大值的时间和内存方法如下:

  1. 对于堆栈中的每个元素,让我们将最大值存储在元素下面。
  2. 当push元素时,其存储(最大值)值将为max(st.top().value, st.top().maxValue)
  3. 当弹出一个元素时,不需要改变任何东西。

所以你可以在O(1)时间和内存复杂度中获得堆栈内所有元素的最大值。

伪代码:

class StackWithMax
{
struct node
{
    int value; // an actual value;
    int maxValue; // maximum of below elements
};
stack<node> st;
public:
void pop()
{
    st.pop();
}
void push(const int &val)
{
   node newNode;
   newNode.value = val;
   newNode.maxValue = (st.empty() == true ? -INFINITY : max(st.top().maxValue, st.top().value) );
   st.push(newNode);
}
int maxStackValue() const
{
    assert(st.empty() == false);
    return st.top().maxValue;
}
};

既然您已经有了一个工作代码,下面是您需要分析的内容。

  1. 现有解决方案的时间复杂度和空间复杂度是多少?
  2. 您可能已经知道,时间和空间之间存在权衡,您可以使用更多的空间来实现更好的时间复杂度吗?

我要做的是查看整个堆栈并保存答案,然后使用第二个堆栈来重建原始的。

int Sorter:: getMax(){
    if(a.empty)
    {
        //handle this however you see fit
    }
    int res = a.top;
    //search for the maximum
    while(!a.empty()){
        if(a.top() > res){
            res = a.top();
        }
        c.push(a.top());
        a.pop();
    }
    //restore the original stack
    while(!c.empty()){
        a.push(c.top());
        c.pop();
    }
    return res;
}

顺便说一句,"a"answers"c"是不好的变量名。我保持它们和你的代码一致。你可能应该用一些更有描述性的东西

我认为如果允许临时变量,那么它会变得更容易。
算法:

将栈A的顶部元素放入临时变量temp=StackA.top();
2. 从栈A中取出一个元素,并检查它是否大于临时变量的值。
2.1如果是,复制该值到temp,并将其压入栈b。
2.2否则直接将值压入栈b
3.重复步骤2,直到堆栈A为空

我知道这看起来像是一个显而易见的(没有什么特别的)解决方案。但是它保留了堆栈中的元素,当然如果你想让它们保持相同的顺序那么你可以再添加一步来复制所有元素取出堆栈B中的所有元素并将其推回堆栈a