503.下一个更大元素II增加Go版本一解法

This commit is contained in:
markwang
2024-10-23 16:19:36 +08:00
parent d04090f22a
commit 6eb35a9737

View File

@ -213,6 +213,40 @@ class Solution:
### Go:
```go
// 版本一
func nextGreaterElements(nums []int) []int {
// 拼接一个新的nums
numsNew := make([]int, len(nums) * 2)
copy(numsNew, nums)
copy(numsNew[len(nums):], nums)
// 用新的nums大小来初始化result
result := make([]int, len(numsNew))
for i := range result {
result[i] = -1
}
// 开始单调栈
st := []int{0}
for i := 1; i < len(numsNew); i++ {
if numsNew[i] < numsNew[st[len(st)-1]] {
st = append(st, i)
} else if numsNew[i] == numsNew[st[len(st)-1]] {
st = append(st, i)
} else {
for len(st) > 0 && numsNew[i] > numsNew[st[len(st)-1]] {
result[st[len(st)-1]] = numsNew[i]
st = st[:len(st)-1]
}
st = append(st, i)
}
}
result = result[:len(result)/2]
return result
}
```
```go
// 版本二
func nextGreaterElements(nums []int) []int {
length := len(nums)
result := make([]int,length)