原题链接在这里:https://leetcode.com/problems/next-greater-element-ii/

题目:

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.

题解:

Next Greater Element I进阶版.

一般这类带环的一种常见做法是加长一倍. 这里就是把nums 走两边.

 没用HashMap<Integer, Integer>是因为nums里会有duplicate. 这里的Stack<Integer> stk 存的是element index 而不是element, 需要index来填res.

Time Complexity: O(n), n = nums.length.

Space: O(n), res size.

AC Java:

 1 class Solution {
 2     public int[] nextGreaterElements(int[] nums) {
 3         if(nums == null || nums.length == 0){
 4             return nums;
 5         }
 6         
 7         int len = nums.length;
 8         int [] res = new int[len];
 9         Stack<Integer> stk = new Stack<Integer>();
10         
11         for(int i = len*2-1; i>=0; i--){
12             int index = i%len;
13             while(!stk.isEmpty() && nums[index]>=nums[stk.peek()]){
14                 stk.pop();
15             }
16             
17             if(i<len){
18                 res[index] = stk.isEmpty() ? -1 : nums[stk.peek()];        
19             }
20             
21             stk.push(index);
22         }
23         
24         return res;
25     }
26 }

 跟上Next Greater Element III.

相关文章: