题目描述

给定一个长度为N的整数数列,输出每个数左边第一个比它小的数,如果不存在则输出-1。

输入格式

第一行包含整数N,表示数列长度。

第二行包含N个整数,表示整数数列。

输出格式

共一行,包含N个整数,其中第i个数表示第i个数的左边第一个比它小的数,如果不存在则输出-1。

数据范围

1≤N≤105
1≤数列中元素≤109

输入样例:

5
3 4 2 7 5

输出样例:

-1 3 -1 2 2

C ++代码描述1-----单调栈实现方式1----模拟栈

#include <iostream>

using namespace std;

const int N = 100010;

//用数组模拟栈
int stk[N], tt;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n;
    cin >> n;

    for(int i = 0; i < n; i ++){
        int x;
        cin >> x;

        while(tt && stk[tt] >= x)   tt --;//若栈顶元素 >= 当前元素,弹出栈顶元素
        if(tt)  cout << stk[tt] << ' ';//栈不为空,输出栈顶元素
        else cout << "-1" << ' ';
        stk[++ tt] = x;//将当前元素加到栈顶
    }

    return 0;
}

C ++代码描述2-----单调栈实现方式2----STL

#include <iostream>
#include <stack>

using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);

    stack <int> s;
    int n;
    cin >> n;

    for(int i = 0; i < n; i ++){
        int x;
        cin >> x;

        while(!s.empty() && s.top() >= x)   s.pop();//若栈顶元素 >= 当前元素,弹出栈顶元素
        if(s.empty())   cout << "-1" << ' ';//栈不为空,输出栈顶元素
        else cout << s.top() << ' ';
        s.push(x);//将当前元素加到栈顶
    }

    return 0;
}