503. Next Greater Element II
Input: nums = [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number.
The second 1's next greater number needs to search circularly, which is also 2.Input: nums = [1,2,3,4,3]
Output: [2,3,4,-1,4]class Solution {
public int[] nextGreaterElements(int[] nums) {
int len = nums.length;
int[] res = new int[len];
Arrays.fill(res, -1);
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < len * 2; i++) {
int index = i % len;
while (!stack.isEmpty() && nums[stack.peek()] < nums[index]) {
res[stack.peek()] = nums[index];
stack.pop();
}
if (i < len) stack.push(index);
}
return res;
}
}Last updated