|
| 1 | +package com.stevesun.solutions; |
| 2 | + |
| 3 | +import java.util.Stack; |
| 4 | + |
| 5 | +/** |
| 6 | + * Given a circular array (the next element of the last element is the first element of the array), |
| 7 | + * print the Next Greater Number for every element. |
| 8 | + * The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, |
| 9 | + * which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number. |
| 10 | +
|
| 11 | + Example 1: |
| 12 | + Input: [1,2,1] |
| 13 | + Output: [2,-1,2] |
| 14 | + Explanation: The first 1's next greater number is 2; |
| 15 | + The number 2 can't find next greater number; |
| 16 | + The second 1's next greater number needs to search circularly, which is also 2. |
| 17 | + Note: The length of given array won't exceed 10000. |
| 18 | + */ |
| 19 | +public class NextGreaterElementII { |
| 20 | + |
| 21 | + //Credit: https://discuss.leetcode.com/topic/77881/typical-ways-to-solve-circular-array-problems-java-solution |
| 22 | + //Note: we store INDEX into the stack, reversely, the larger index put at the bottom of the stack, the smaller index at the top |
| 23 | + public int[] nextGreaterElements(int[] nums) { |
| 24 | + if (nums == null || nums.length == 0) return nums; |
| 25 | + int len = nums.length; |
| 26 | + Stack<Integer> stack = new Stack<>(); |
| 27 | + for (int i = len-1; i >= 0; i--) { |
| 28 | + stack.push(i);//push all indexes into the stack reversely |
| 29 | + } |
| 30 | + int[] result = new int[len]; |
| 31 | + for (int i = len-1; i >= 0; i--) { |
| 32 | + result[i] = -1;//initialize it to be -1 in case we cannot find its next greater element in the array |
| 33 | + while (!stack.isEmpty() && (nums[stack.peek()] <= nums[i])) { |
| 34 | + stack.pop(); |
| 35 | + } |
| 36 | + if (!stack.isEmpty()) { |
| 37 | + result[i] = nums[stack.peek()]; |
| 38 | + } |
| 39 | + stack.push(i); |
| 40 | + } |
| 41 | + return result; |
| 42 | + } |
| 43 | + |
| 44 | + //credit: https://leetcode.com/articles/next-greater-element-ii/ |
| 45 | + public int[] nextGreaterElements_editorial_solution(int[] nums) { |
| 46 | + int[] result = new int[nums.length]; |
| 47 | + Stack<Integer> stack = new Stack<>(); |
| 48 | + for (int i = nums.length*2-1; i>=0 ;i--) { |
| 49 | + while (!stack.isEmpty() && nums[stack.peek()] <= nums[i%nums.length]) { |
| 50 | + stack.pop(); |
| 51 | + } |
| 52 | + result[i%nums.length] = stack.isEmpty() ? -1 : nums[stack.peek()]; |
| 53 | + stack.push(i%nums.length); |
| 54 | + } |
| 55 | + return result; |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments