gpt4 book ai didi

c++ - 所有最近的较小值

转载 作者:行者123 更新时间:2023-11-28 03:38:23 25 4
gpt4 key购买 nike

我想构建我的代码来解决所有最近的较小值问题,这是我为此所做的努力

#include<iostream>
#include<stack>
using namespace std;
void all_smallest(int a[],int n)
{
stack<int>s;
for(int x=0;x<n;x++)
{
while(!s.empty() && s.top()>=a[x])
{
cout<<s.top();
s.pop();
}
if(s.empty()){ continue;}
else
{
s.push(a[x]);
}

}
}

int main()
{
int a[]={0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};
int n=sizeof(a)/sizeof(a[0]);
all_smallest(a,n);

return 0;
}

它编译,但没有输出,为什么?请帮助我

最佳答案

正在检查 Wikipedia你没有正确实现算法。它应该是这样的:

    #include<iostream>
#include<stack>
using namespace std;
void all_smallest(int a[],int n)
{
stack<int>s;
for(int x=0;x<n;x++)
{
while(!s.empty() && s.top()>=a[x])
{
s.pop();
}
if(!s.empty())
{
cout<<s.top();
}
s.push(a[x]);
}
}

int main()
{
int a[]={0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};
int n=sizeof(a)/sizeof(a[0]);
all_smallest(a,n);
cout << "\n";
return 0;
}

输出:

    004022601151337

关于c++ - 所有最近的较小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10178734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com