Skip to content

Latest commit

 

History

History
66 lines (45 loc) · 957 Bytes

830. 单调栈.md

File metadata and controls

66 lines (45 loc) · 957 Bytes

830. 单调栈

题目

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

输入格式

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

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

输出格式

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

数据范围

$1≤N≤10^5$ $1≤数列中元素≤10^9$

输入样例

5
3 4 2 7 5

输出样例

-1 3 -1 2 2

AC代码

#include <iostream>
#include <algorithm>

using namespace std;

int n;
int stk[100010],tt=-1;

int main()
{
    cin >> n;
    while(n--)
    {
        int x;
        cin >> x;
        while(tt!=-1&&stk[tt]>=x) tt--;
        if(tt==-1) printf("-1 ");
        else cout << stk[tt] << ' ';
        stk[++tt] = x;
    }
    return 0;
}

解题思路

单调栈操作