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.
下一个更大的元素II。
版本一传送门在此。这个题依然是找数组中往右比当前元素更大的元素,但是版本二改了一个设定,需要假设input是一个环,也就是说数组最后一个元素在res里面的结果很有可能不是-1。
思路依然是单调栈,去看栈顶元素是否比当前元素小,若栈顶元素小则弹出栈并存到结果集res里面;若栈顶元素大则还是把当前元素的index入栈。单调栈类型的题绝大部分放入栈的都是遍历数组的index。这道题因为是环的关系所以遍历两遍input数组即可。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int[] nextGreaterElements(int[] nums) { 3 int len = nums.length; 4 int[] res = new int[len]; 5 Arrays.fill(res, -1); 6 Stack<Integer> stack = new Stack<>(); 7 for (int i = 0; i < len * 2; i++) { 8 int cur = nums[i % len]; 9 while (!stack.isEmpty() && nums[stack.peek()] < cur) { 10 res[stack.pop()] = cur; 11 } 12 // when loop for the first time 13 if (i < len) 14 stack.push(i); 15 } 16 return res; 17 } 18 }
JavaScript实现
1 /** 2 * @param {number[]} nums 3 * @return {number[]} 4 */ 5 var nextGreaterElements = function (nums) { 6 let len = nums.length; 7 let res = new Array(len).fill(-1); 8 let stack = []; 9 for (let i = 0; i < nums.length * 2; i++) { 10 let cur = nums[i % len]; 11 while (stack.length > 0 && nums[stack[stack.length - 1]] < cur) { 12 res[stack.pop()] = cur; 13 } 14 if (i < len) { 15 stack.push(i); 16 } 17 } 18 return res; 19 };