503. 下一个更大元素 II
给定一个循环数组 nums ( nums[nums.length - 1] 的下一个元素是 nums[0] ),返回 nums 中每个元素的 下一个更大元素 。
数字 x 的 下一个更大的元素 是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1 。
答案
class Solution {
public int[] nextGreaterElements(int[] nums) {
int length = nums.length;
int[] ans = new int[length];
Deque<Integer> stack = new LinkedList<Integer>();
for (int i = 0; i < length; i++) {
ans[i] = -1;
int t = nums[i];
while (!stack.isEmpty() && t > nums[stack.peek()]) {
int prevIndex = stack.pop();
ans[prevIndex] = t;
}
stack.push(i);
}
int i = 0;
while (!stack.isEmpty() && i < length) {
if (nums[i] > nums[stack.peek()]) {
ans[stack.pop()] = nums[i];
} else {
i++;
}
}
return ans;
}
}