法1:单调栈+循环数组
参考思路:本题解答
Python
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
n = len(nums)
stack = []
res = [-1] * n
for i in range(n*2-1, -1, -1):
while stack and stack[-1] <= nums[i%n]:
stack.pop()
if stack:
res[i%n] = stack[-1]
stack.append(nums[i%n])
return res
Java
class Solution {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] res = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 2 * n - 1; i >= 0; --i) { // 循环数组处理!!!
while (!stack.isEmpty() && nums[i % n] >= stack.peek()) {
stack.pop();
}
res[i % n] = stack.isEmpty() ? -1 : stack.peek();
stack.push(nums[i % n]);
}
return res;
}
}