单调栈 O(n) AC
思路:
考虑暴力统计的话,时间复杂度是O(n^2)
故考虑使用单调栈,当需要寻找第i个元素之前的首个小于a[i]的元素,维护一个单调上升的栈
import java.util.Scanner;
public class Main {
int N = 100000 + 10;
int[] st = new int[N];
int tt = -1;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) nums[i] = sc.nextInt();
Main ins = new Main();
int[] ans = ins.solve(nums);
for (int i = 0; i < n; i++) System.out.print(ans[i] + " ");
sc.close();
}
private int[] solve(int[] a) {
int n = a.length;
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
while (tt != -1 && st[tt] >= a[i]) tt--;
if (tt == -1) {
ans[i] = -1;
} else {
ans[i] = st[tt];
}
tt++;
st[tt] = a[i];
}
return ans;
}
}