使用一个内存集数组和单个堆栈在 O(n) 中查找数组的下一个更大元素
find next greater element of a array in O(n) using one memset array and a single stack
我的代码不适用于输入:
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
相关文章:
- 在数组中查找总计
- 在二维数组中查找最小值和最大值?
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 查找自动生成键并具有线性内存消耗的小型关联数组
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 如何使用数组查找标准偏差
- 从列表到数组C 查找模式或最常见的数字
- 12个元素的数组 - 查找计数实践
- 使用数组查找HCF,获取未知输出(C )
- C++constexpr数组查找:内存开销?其他问题
- C++字符数组查找/替换字符
- 动态数组查找能力
- 用.用数组查找.C++
- 使用数组查找最大值
- 字典查找与数组查找;数组分配与字典分配
- 使用数组查找最接近的数字C++,浮点
- 定义一个非常大的数组(查找表)的最佳方式是什么
- Std::数组查找最大值函数
- Python在简单数组查找上的小循环的性能问题