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:

1
2
3
4
5
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.

思路

最开始以为O(n^2)的方法是可以使用的,但是不巧,这个答案是超时的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution(object):
def nextGreaterElements(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = []
for i, cur in enumerate(nums):
hasFound = False
for j, big in enumerate(nums[i:]):
if (cur < big):
res.append(big)
hasFound = True
break
if (hasFound):
continue
for j, big in enumerate(nums[:i]):
if (cur < big):
res.append(big)
hasFound = True
break
if (hasFound):
continue
else:
res.append(-1)
return res

接下来试一下stack的方法。基本的思路就是将所有的元素按照一定规律入栈和出栈,参见496题的基本方法。

首先要确定,这是一个循环的list,所以做两次O(n)的循环比较妥当。这样list尾部的元素还有机会和list头部的元素来进行比较。

其次,stack里面存放的应该是nums里面的元素index,每一个元素都需要入一次栈,和之后的元素进行比较。要注意的是,如果栈里面存有元素,那说明栈里面的元素后一个应当是大于前一个的。所以在出栈的时候,需要利用循环来判断最新访问的元素nums[index]是否大于栈里面的所有元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
def nextGreaterElements(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
length = len(nums)
res = []
stack = []
for i in range(length):
res.append(-1)
for i in range(2 * length):
index = i % length
if (stack):
while (nums[stack[-1]] < nums[index]):
res[stack[-1]] = nums[index]
stack.pop()
if (not stack):
break
if (i < length):
stack.append(i)
return res