给定一个环形数组(最后一个数的下一个数是数组的第一个元素),为每个元素打印下一个更大的元素。数字x的下一个更大的数是遍历数组的过程中出现的第一个更大的数字,这意味着可以循环搜索以查找下一个更大的数字,如果不存在则输出-1
class Solution:
def nextGreaterElements(self,nums):
if not nums:
return []
stack,res = [],[-1 for i in range(len(nums))]
for i in range(len(nums)):
if stack and nums[i]>nums[stack[-1]]:
while stack and nums[i] > nums[stack[-1]]:
pop_index = stack.pop()
res[pop_index] = nums[i]
stack.append(i)
for i in range(len(nums)):
if stack and nums[i] > nums[stack[-1]]:
while stack and nums[i] > nums[stack[-1]]:
pop_index = stack.pop()
res[pop_index] = nums[i]
stack.append(i)
if nums[stack[0]] == nums[stack[-1]]:
break
return res