2344. 编号最大的高能力者
思路:单调栈
package ahwoj;
import java.util.Scanner;
import java.util.Stack;
/**
* 找到每个元素的左侧,等级最大且离得最近的元素索引
* 9
* 5 9 3 1 1 9 6 8 1
*
* 5 9 3 1 1 9
* stack: 0 0出 1 2 3出 2
* res: 0 0 1 2 2
*/
public class LevelMax2344 {
// 单调栈, 如果栈顶元素>current,入栈,记录索引,否则,出栈
public static int[] maxLevel(int[] level) {
Stack stack = new Stack<Integer>();
int[] res = new int[level.length];
for (int i = 0; i < level.length; i++) {
if (i == 0) {
stack.add(i);
continue;
}
while (!stack.isEmpty() && (level[(int)stack.peek()]) <= level[i]) {
stack.pop();
}
res[i] = stack.isEmpty() ? 0 : (int)stack.peek() + 1;
stack.add(i);
}
return res;
}
public static void main(String[] args) {
// int[] level = new int[]{5,9,3,1,1,9,6,8,1};
Scanner scanner = new Scanner(System.in);
int len = Integer.parseInt(scanner.nextLine());
String s = scanner.nextLine();
String[] arr = s.split(" ");
int[] level = new int[len];
for (int i = 0; i < len; i++) {
level[i] = Integer.parseInt(arr[i]);
}
int[] res = maxLevel(level);
for (int i = 0; i < res.length; i++) {
if (i == res.length - 1) {
System.out.print(res[i]);
} else {
System.out.print(res[i] + " ");
}
}
}
}