AcWing 830. 单调栈(Monotonic stack Module) Described by Java

Today we again learn the monotonic stack module , it is very difficult to think.
The problem :
给定一个长度为N的整数数列,输出每个数左边第一个比它小的数,如果不存在则输出-1。

输入格式
第一行包含整数N,表示数列长度。

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

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

数据范围
1≤N≤105
1≤数列中元素≤109
输入样例:
5
3 4 2 7 5
输出样例:
-1 3 -1 2 2


The module code :

import java.util.*;
import java.io.*;

public class Main {
    static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    static PrintWriter pw = new PrintWriter(System.out);
    static Scanner sn = new Scanner(System.in);
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static Stack<Integer> stack = new Stack<>();
    static int n, nums[];

    public static void main(String[] args) throws Exception {
        st.nextToken();
        n = (int) st.nval;
        nums = new int[n];
        for (int i = 0; i < n; i++) {
            st.nextToken();
            nums[i] = (int) st.nval;
        }
        for (int i = 0; i < n; i++) {
            while (!stack.empty() && stack.peek() >= nums[i]) stack.pop();
            if (!stack.empty()) System.out.print(stack.peek() + " ");
            else System.out.print(-1 + " ");
            stack.push(nums[i]);
        }
    }
}

你可能感兴趣的:(数据结构)