AcWing 830. 单调栈
原题链接
简单
作者:
DongTang
,
2022-12-10 00:32:42
,
所有人可见
,
阅读 157
java 代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] nums = br.readLine().split(" ");
int[] arr = new int[n];
int l = 0;
for(String num : nums){
arr[l++] = Integer.parseInt(num);
}
int[] res = new int[n];
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < n; ++i) {
while (!stack.isEmpty() && stack.peek() >= arr[i]){
stack.pop();
}
res[i] = stack.isEmpty() ? -1 : stack.peek();
System.out.print(res[i] + " ");
stack.push(arr[i]);
}
}
}