---
# System prepended metadata

title: 0503. Next Greater Element II
tags: [Leetcode, FaceBook, Medium, Stack]

---

# 0503. Next Greater Element II
###### tags: `Leetcode` `Medium` `Stack` `FaceBook`
Link: https://leetcode.com/problems/next-greater-element-ii/
## 思路
O(N) O(N)
**单调栈经典题 找左边/右边 第一个比它大/比它小的数字**
**建议都用index存**
和[0496. Next Greater Element I](https://hackmd.io/WBoT6EQtQFu3hB9ZltGfCA)很像
stack 遍历两遍
## Code
```java=
class Solution {
    public int[] nextGreaterElements(int[] nums) {
        Stack<Integer> stack = new Stack<>();
        int[] res = new int[nums.length];
        Arrays.fill(res, -1);
        
        for(int i = 0;i < nums.length*2;i++){
            while(!stack.isEmpty() && nums[stack.peek()]<nums[i % nums.length]){
                res[stack.pop()] = nums[i % nums.length];
            }
            stack.push(i % nums.length);
        }
        
        return res;
    }
}
```