https://leetcode.com/problems/next-greater-element-ii/
Example 1:
Input: nums = [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.
Example 2:
Input: nums = [1,2,3,4,3]
Output: [2,3,4,-1,4]
nums2 = nums拉長兩倍
初始化一個reuslt array,長度為nums,fill -1
初始化一個stack
for i, num in nums2
return result
func nextGreaterElements(nums []int) []int {
nums2 := append(nums, nums...)
result := make([]int, len(nums))
for i := range result {
result[i] = -1
}
stack := []int{}
for i, num := range nums2 {
for len(stack) > 0 && num > nums2[stack[len(stack)-1]] {
top := stack[len(stack)-1]
stack = stack[:len(stack)-1]
result[top%len(nums)] = num
}
stack = append(stack, i)
}
return result
}