1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public int[] nextGreaterElements(int[] nums) { int[] res = new int[nums.length]; Arrays.fill(res, -1);
Stack<Integer> decreaseStack = new Stack<>(); for (int i = 0; i < nums.length * 2 - 1; i++) { while (!decreaseStack.isEmpty() && nums[i % nums.length] > nums[decreaseStack.peek()]) { int lowerIndex = decreaseStack.pop(); res[lowerIndex] = nums[i % nums.length]; }
decreaseStack.push(i % nums.length); }
return res; } }
|
References
503. Next Greater Element II