题目是:给定一个可能含有重复值的数组 arr,找到每一个 i 位置左边和右边离 i 位置最近且值比 arr[i] 小的位置。返回所有位置相应的信息。
我的思路是:用一个栈来存储arr[i]左边的数组,用另一个栈存储arr[i]右边的数组,然后从两个栈顶分别与arr[i]存放的数值比较,若相等,则输出第一个比arr[i]小的数对应的数列序号
下面是我写的代码
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<int> s;
stack<int> t;
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
s.push(a[i]);
}
for(int i=0;i<n;i++)
{
while(s.top()!=a[i]){
t.push(s.top());
s.pop();
}
s.pop();
if(s.empty()){
cout<<"-1"<<" ";
}
else{
while(s.top()>=a[i]){
s.pop();
}
if(s.empty()){
cout<<"-1"<<" ";
}
else{
for(int m=0;m<n;m++){
if(a[m]==s.top())
cout<<m<<" ";
}
}
}
if(t.empty()){
cout<<"-1"<<endl;
}
else{
while(t.top()>=a[i]){
t.pop();
}
if(t.empty()){
cout<<"-1"<<endl;
}
else{
for(int k=0;k<n;k++){
if(a[k]==t.top())
cout<<k<<endl;
}
}
}
while(!s.empty()){
cout<<s.top()<<endl;
s.pop();
}
for(int p=0;p<n;p++){
s.push(a[p]);
}
while(!t.empty()){
cout<<t.top()<<endl;
t.pop();
}
}
return 0;
}
样例输入:
7
3 4 1 5 6 2 7
样例输出:
-1 2
0 2
-1 -1
2 5
3 5
2 -1
5 -1
##其实前两行都能正常输出,不知道为啥输出第三行的时候卡了很久,然后OJ(Oline Judge)说数组越界了,我检查了好久,其实这道题我用简单的循环早就做出来了,就是想换一种思路试试,没想到卡在这里了,希望各位大佬们帮我看看,帮小弟指点一下迷津,谢谢了!