给定一个可能含有重复值的数组 arr,找到每一个 i 位置左边和右边离 i 位置最近且值比 arr[i] 小的位置。返回所有位置相应的信息。

题目是:给定一个可能含有重复值的数组 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)说数组越界了,我检查了好久,其实这道题我用简单的循环早就做出来了,就是想换一种思路试试,没想到卡在这里了,希望各位大佬们帮我看看,帮小弟指点一下迷津,谢谢了!

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值