Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.
Example 1:
Input: [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.
Note: The length of given array won't exceed 10000.
1 public class Solution { 2 public int[] nextGreaterElements(int[] nums) { 3 int n = nums.length; 4 int[] result = new int[n]; 5 6 Stack<Integer> stack = new Stack<>(); 7 for (int i = n - 1; i >= 0; i--) { 8 if (stack.isEmpty()) { 9 result[i] = getValue(nums, i, i); 10 } else { 11 if (nums[i] >= stack.peek()) { 12 while (!stack.isEmpty() && stack.peek() <= nums[i]) { 13 stack.pop(); 14 } 15 if (stack.isEmpty()) { 16 result[i] = getValue(nums, n - 1, i); 17 stack.push(nums[i]); 18 continue; 19 } 20 } 21 result[i] = stack.peek(); 22 } 23 stack.push(nums[i]); 24 } 25 return result; 26 } 27 28 private int getValue(int[] nums, int start, int i) { 29 int n = nums.length, index = (start + 1) % n; 30 while (index != i) { 31 if (nums[index] > nums[i]) return nums[index]; 32 index = (index + 1) % n; 33 } 34 return -1; 35 } 36 }