503. Next Greater Element II

https://leetcode.com/problems/next-greater-element-ii/

还是next greater element的味道,只不过这一次,nums是一个circular array, 所以把nums粘了两遍

class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        nums2 = nums + nums
        n = len(nums)
        stack = []
        res = [-1] * n
        for i in range(2*n):
            while stack and nums2[stack[-1]] < nums2[i]:
                curr = stack.pop()
                if curr < n:
                    res[curr] = nums2[i]
            stack.append(i)
        return res

Last updated

Was this helpful?