Golang | Leetcode Golang题解之第503题下一个更大元素II-题解:

时间:2024-10-24 07:49:50
func nextGreaterElements(nums []int) []int {
    n := len(nums)
    ans := make([]int, n)
    for i := range ans {
        ans[i] = -1
    }
    stack := []int{}
    for i := 0; i < n*2-1; i++ {
        for len(stack) > 0 && nums[stack[len(stack)-1]] < nums[i%n] {
            ans[stack[len(stack)-1]] = nums[i%n]
            stack = stack[:len(stack)-1]
        }
        stack = append(stack, i%n)
    }
    return ans
}