classSolution(object):
def nextGreaterElements(self, nums):"""
:type nums: List[int]:rtype: List[int]"""
# 单调栈+哈希表,跟LC496的区别是,这次是循环数组
# 比较笨的办法就是在给出的数组后面接上数组的[0,n-1],这样就算人工构造的循环数组了
# 其实,可以直接用下标取模来实现
n =len(nums)
res =[-1]* n
stack =list()for i in range(2*n-1):while stack and nums[i%n]> nums[stack[-1]]:
res[stack.pop()]= nums[i%n]
stack.append(i%n)return res
# 逆序
n =len(nums)
res =[-1]*n
stack =list()for i in range(2*n-1,-1,-1):while stack and nums[stack[-1]]<= nums[i%n]:
stack.pop()
res[i%n]= nums[stack[-1]]if stack else-1
stack.append(i%n)return res