Next Greater Element II
Stack
Medium
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.
Analysis
此题和Daily Temperatures很像,但是不同之处在于这里允许search circularly,因此常规的做法就是将搜索空间从原先的nums.length,拓展成为2 * nums.length
。
其余的要点就是保持一个单调栈,monotonous stack,并且注意数组下标要对nums.length
取模,以适应circular的应用场景。
Solution
Monotonous Stack + Circular Array Search (21 ms, faster than 94.64%)
class Solution {
public int[] nextGreaterElements(int[] nums) {
int len = nums.length;
int[] res = new int[len];
Deque<Integer> stack = new ArrayDeque<>();
Arrays.fill(res, -1);
for (int i = 0; i < 2 * len; i++) {
while (!stack.isEmpty() && nums[i % len] > nums[stack.peek()]) {
int idx = stack.pop();
res[idx] = nums[i % len];
}
stack.push(i % len);
}
return res;
}
}
Time complexity :
O(n)
. Only two traversals of thenums
array are done. Further, at most2n
elements are pushed and popped from the stack.Space complexity :
O(n)
. Astack
of sizen
is used.res
array of sizen
is used.
A little optimization with i < len
and checking if stack.isEmpty()
then break
i < len
and checking if stack.isEmpty()
then break
class Solution {
public int[] nextGreaterElements(int[] nums) {
int len = nums.length;
int[] res = new int[len];
Deque<Integer> stack = new ArrayDeque<>();
Arrays.fill(res, -1);
for (int i = 0; i < 2 * len; i++) {
while (!stack.isEmpty() && nums[i % len] > nums[stack.peek()]) {
int idx = stack.pop();
res[idx] = nums[i % len];
}
if (i < len) {
stack.push(i);
}
if (stack.isEmpty()) {
break;
}
}
return res;
}
}
Last updated
Was this helpful?