c++ - 将最小出现次数留在堆栈底部的函数
问题描述
我正在尝试编写一个堆栈,以便所有出现的最小元素都位于堆栈的底部,而其他元素的顺序保持不变。例如,如果我有堆栈 [4,3,1,5,8,1,4] 它将变为 [4,3,5,8,4,1,1],但我的问题是顺序更改所以我会得到这样的东西[4,5,3,4,8,1,1]
#include <iostream>
#include <stack>
using namespace std;
void minstack(stack<int> &s)
{
stack<int> t1,t2;
int count=0,min;
if(!s.empty())
{
while(!s.empty())
{
if(s.top() <min)
{ min=s.top();
count=0;
}
t1.push(s.top()); s.pop();
count++;
}
for(int i = 0 ; i<count;i++)
{
s.push(min);
}
while(!t1.empty())
{
if(t1.top()!=min);
{ s.push(t1.top());
}
t1.pop();
}
}
}
int main()
{
stack <int> s;
s.push(4);
s.push(3);
s.push(1);
s.push(5);
s.push(8);
s.push(1);
s.push(4);
minstack(s);
while(!s.empty())
{
cout<<s.top()<<" "; s.pop();
}
}
解决方案
这是一个想法。首先,我们需要找到堆栈的最小元素。定义一个临时堆栈t
。我们现在将一个一个地弹出所有元素s
并将它们推入t
. 同时,min
在弹出过程中跟踪最小值和迄今为止遇到的次数count
。完成此操作后,请注意您将在t
和 具有min
和中具有相反的元素顺序count
。现在我们将count
value 元素的数量推min
回s
. 然后开始弹出并从到推t
送到s
除了等于的元素min
。
推荐阅读
- php - Wordpress 多站点:警告:检测到现有的 WordPress 网络
- swift - What is the correct syntax for using Publishers.debounce() in Swift Combine?
- dns - Request to Cloudflare DNS from Cloudflare worker not returning the DNS result
- c# - 在我编辑其 itemssource(这是一个 DB)后,我无法更新列表框的内容
- php - Sage Accounting API UnexpectedError
- asp.net-mvc - 自定义 EPiServer 表单:成功消息未显示为 HTML 代码
- reactjs - 有没有办法在 onClick 方法中调用多个函数而无需提供参数?
- bash - 处理中的替换命令。ebextensions
- python-3.x - 使用 Gensim 在 Python 中重新训练预训练的词嵌入
- azure-active-directory - 使用 Azure AD 进行 Azure 应用服务身份验证 - 为什么需要 AD 应用?