503. 下一个更大元素 II

  1. class Solution {
  2. public int[] nextGreaterElements(int[] nums) {
  3. if (nums == null || nums.length == 0)
  4. return new int[0];
  5. int len = nums.length;
  6. Deque<Integer> stack = new LinkedList<>();
  7. int[] ans = new int[len];
  8. Arrays.fill(ans, -1);
  9. for (int i = 0; i < 2 * len - 1; i++) {
  10. while (!stack.isEmpty() && nums[i % len] > nums[stack.peek()]) {
  11. ans[stack.pop()] = nums[i % len];
  12. }
  13. stack.push(i % len);
  14. }
  15. return ans;
  16. }
  17. }