一.原题如下:

二.解题思路
使用单调栈(递减),
循环数组解决方案:将数组长度翻倍,所有涉及下标取值的索引都需要进行数组长度取模。
单调栈需要倒序遍历,并且有一套固定代码模板。
同样使用单调栈代码模板,只是循环操作有个别变化。
public static int[] monotonicStackHelper(int[] nums) {
int size = nums.length;
int[] res = new int[size];
Stack<Integer> st = new Stack<>();
for (int i = size * 2 - 1; i >= 0; i--) {
while (!st.isEmpty() && st.peek() <= nums[i % size]) {
st.pop();
}
res[i % size] = st.isEmpty() ? -1 : st.peek();
st.push(nums[i % size]);
}
return res;
}
三.完整题解
public static int[] nextGreaterElements(int[] nums) {
return monotonicStackHelper(nums);
}