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:
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%)
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
Last updated