给定一个长度为 N 的整数数列,输出每个数左边第一个比它小的数,如果不存在则输出 −1。
输入格式
第一行包含整数 N,表示数列长度。
第二行包含 N 个整数,表示整数数列。
输出格式
共一行,包含 N 个整数,其中第 i 个数表示第 i 个数的左边第一个比它小的数,如果不存在则输出 −1。
数据范围
1≤N≤105
1≤数列中元素≤109
输入样例:
5
3 4 2 7 5
输出样例:
-1 3 -1 2 2
#include<iostream>
using namespace std;
const int N=100010;
int s[N],tt;
int n;
int main(){
cin>>n;
for(int i=0;i<n;i++)
{
int x; cin>>x;
while(tt && s[tt]>=x) tt--;
if(tt) cout<<s[tt]<<' ';
else cout<<"-1"<<' ';
s[++tt] = x;
}
return 0;
}
#include<iostream>
#include<stack>
using namespace std;
const int N = 1e5+10;
int a[N];
stack<int> s;
int main() {
int n;
cin >> n;
for(int i = 0;i < n;i++) {
cin >> a[i];
}
s.push(a[0]);
cout << "-1" << ' ';
for(int i = 1;i < n;i++) {
//使用一个栈来,判断是s[]内元素的大小关系,若栈顶大于等于s[i]则出栈,否则输出栈顶
while( !s.empty() && a[i] <= s.top() ) {
s.pop(); // 出栈
}
if(s.empty()) cout << "-1 ";
else cout << s.top() << " ";
s.push(a[i]);//若if语句判断“-1”,入栈,此时栈顶改变为入栈的数
}
return 0;
}