题目:
思路:
做法:单调栈+循环数组
因为是循环数组所以一般都能想到取余操作,发现只要遍历数组的两遍,即可找到答案
代码:
class Solution {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] ret = new int[n];
Arrays.fill(ret, -1);
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < n * 2 - 1; i++) {
while (!stack.isEmpty() && nums[stack.peek()] < nums[i % n]) {
ret[stack.pop()] = nums[i % n];
}
stack.push(i % n);
}
return ret;
}
}