使用一个内存集数组和单个堆栈在 O(n) 中查找数组的下一个更大元素

find next greater element of a array in O(n) using one memset array and a single stack

本文关键字:数组 查找 下一个 元素 单个 一个 内存 堆栈      更新时间:2023-10-16

我的代码不适用于输入:

10 3 *12* 4 2 9 13 0 8 11 1 7 5 6  

其正确输出为:

12 12 *13* 9 9 13 -1 8 11 -1 7 -1 6 -1

代码的输出为:

12 12 *-1* 9 13 13 -1 8 11 -1 7 -1 6 -1

我可以看到,这是因为在while(!s.empty() && a>s.top())部分中我没有存储那些a<s.top()元素的索引值,我想不出任何方法可以这样做。

#include <bits/stdc++.h>
#define ll long long
using namespace std;
int main() {
int t;
cin>>t;
while(t--)
{
ll n;
cin>>n;
ll a,i,c[n];
memset(c,-1,sizeof(c));
stack <int> s;
for(i=0;i<n;i++){
cin>>a;
if(s.empty()){
s.push(a);
}
else{
if(a>s.top()){
int k=i;
while(!s.empty() && a>s.top()){
s.pop();
c[k-1]=a;
k--;
}
s.push(a);
}
else{
s.push(a);
continue;
}
}
}
for(i=0;i<n;i++)
cout<<c[i]<<" ";
cout<<endl;
}
}

你的代码中有一个小错误。更新c[index]=value的值时,index不正确。在处理过程中,您从stack中弹出一些元素并在末尾推送值(例如:位置为 10 的值可以在 0 到 10 之间的任何位置推送(,但在后退过程中,您不知道该值的正确位置是什么。

因此,我在代码中进行了幻灯片更改,跟踪了值的位置以及值本身。所以,当我更新c[index]=value时,我知道s.top()元素的正确索引。

int main() {
int t;
cin>>t;
while(t--)
{
ll n;
cin>>n;
ll a,i,c[n];
memset(c,-1,sizeof(c));
stack < pair<int,int> > s;
for(i=0;i<n;i++){
cin>>a;
if(s.empty()){
s.push({a,i});
}
else{
if(a>s.top().first){
while(!s.empty() && a>s.top().first){
c[s.top().second]=a;
s.pop();
}
s.push({a,i});
}
else{
s.push({a,i});
continue;
}
}
}
for(i=0;i<n;i++)
cout<<c[i]<<" ";
cout<<endl;
}
}

输入和输出:

1                                                                                                                               
15                                                                                                                              
14 10 3 12 4 2 9 13 0 8 11 1 7 5 6                                                                                              
-1 12 12 13 9 9 13 -1 8 11 -1 7 -1 6 -1