通过使用另一个堆栈查找堆栈中的最大值
Finding the maximum value in a stack by using another stack?
我有下面的代码来查找堆栈中的最大值。它正在工作,但我是否应该使用另一种方法来查找最大值,因为在调用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)
查找堆栈最大值的时间和内存方法如下:
- 对于堆栈中的每个元素,让我们将最大值存储在元素下面。
- 当push元素时,其存储(最大值)值将为
max(st.top().value, st.top().maxValue)
- 当弹出一个元素时,不需要改变任何东西。
所以你可以在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;
}
};
既然您已经有了一个工作代码,下面是您需要分析的内容。
- 现有解决方案的时间复杂度和空间复杂度是多少?
- 您可能已经知道,时间和空间之间存在权衡,您可以使用更多的空间来实现更好的时间复杂度吗?
我要做的是查看整个堆栈并保存答案,然后使用第二个堆栈来重建原始的。
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
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 在C++中查找文件
- 模板元程序查找相似的连续类型名称
- 在UNIX系统中使用DIR查找文件的字节大小
- 查找最接近的大于当前数字的数字的索引
- 算法问题:查找从堆栈中弹出的所有序列
- 使用一个内存集数组和单个堆栈在 O(n) 中查找数组的下一个更大元素
- 使用堆栈查找每个元素的下一个更大的元素
- 从堆栈跟踪中查找共享库中的源代码行
- 使用 windbg 查找不在堆栈顶部的函数的函数参数
- 从堆栈指针中查找函数参数值
- c++迷宫解算器(查找所有解决方案)堆栈溢出
- 在 stl 堆栈 cpp 中查找元素
- 任何人都可以在此程序中发现错误(在 2 个通用堆栈中查找相同元素的数量)
- 高效查找应用了数据修改堆栈的缓冲区
- 如何查找未初始化的堆栈变量
- 在x64堆栈中查找RUNTIME_FUNCTION的算法
- 程序简单,没有调用堆栈,"inpossible"查找错误
- 在恒定时间内查找堆栈中的最大元素
- 通过使用另一个堆栈查找堆栈中的最大值