AcWing 830. 单调栈
发布日期:2021-05-07 14:08:27 浏览次数:21 分类:技术文章

本文共 1011 字,大约阅读时间需要 3 分钟。

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

输入格式

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

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

输出格式

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

数据范围

1≤N≤1051≤N≤105

1≤数列中元素≤1091≤数列中元素≤109

输入样例:

53 4 2 7 5

输出样例:

-1 3 -1 2 2
import java.io.*;import java.lang.Integer;class Main{    static int N = 100010;    static int[] st = new int[N];    static int tt = 0;    public static void main(String[] args)throws Exception{                BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));        BufferedWriter buw = new BufferedWriter(new OutputStreamWriter(System.out));                int n = Integer.valueOf(buf.readLine());        String[] params = buf.readLine().split(" ");        for(int i = 0; i < n; ++i){            int x = Integer.valueOf(params[i]);            while(tt > 0 && st[tt] >= x)tt--;            if(tt > 0 && st[tt] < x)buw.write(st[tt] + " ");            else buw.write(-1 + " ");            st[++tt] = x;        }        buw.flush();        buf.close();        buw.close();    }}

 

上一篇:AcWing 154. 滑动窗口
下一篇:AcWing 829. 模拟队列

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2025年03月31日 14时28分47秒