LeetCode-503 Next Greater Element II Solution (with Java)

1. Description:

Notes: 

2. Examples:

3.Solutions:

 1 /**
 2  * Created by sheepcore on 2019-05-10
 3  */
 4 class Solution {
 5     public int[] nextGreaterElements(int[] A) {
 6         int n = A.length, res[] = new int[n];
 7         Arrays.fill(res, -1);
 8         Stack<Integer> stack = new Stack<>();
 9         //We need to loop twice to iterate circularly
10         for (int i = 0; i < n * 2; i++) {
11             while (!stack.isEmpty() && A[stack.peek()] < A[i % n])
12                 res[stack.pop()] = A[i % n];
13             stack.push(i % n);
14         }
15         return res;
16     }
17 }

 

猜你喜欢

转载自www.cnblogs.com/sheepcore/p/12395679.html