代码拉取完成,页面将自动刷新
package main
import "fmt"
func numberOfMountainSeen(height []int) int {
return leftSeen(height) + rightSeen(height)
}
func leftSeen(height []int) int {
stacks := [][]int{{}}
res := 0
for i := 2 ; i < len(height) ; i += 2 {
preStack := stacks[len(stacks)-1]
nowStack := append([]int{},preStack...)
for j := 2 ; j > 0 ; j -- {
if len(nowStack) == 0 {
nowStack = append(nowStack, height[i-j])
continue
}
// 当出现大于栈顶元素时,循环比对进行弹栈
for len(nowStack) > 0 && height[i-j] >= nowStack[len(nowStack)-1] {
nowStack = nowStack[:len(nowStack)-1]
}
nowStack = append(nowStack, height[i-j])
}
stacks = append(stacks, nowStack)
res += len(nowStack)
}
return res
}
func rightSeen(height []int) int {
n := len(height)
start := (n - 1)- (n % 2)
stacks := [][]int{{}}
if n == n - 2 {
stacks[0] = []int{height[n-1]}
}
res := 0
for i := start - 2 ; i >= 0 ; i -= 2 {
preStack := stacks[len(stacks)-1]
nowStack := append([]int{},preStack...)
for j := 2 ; j > 0 ; j -- {
if len(nowStack) == 0 {
nowStack = append(nowStack, height[i+j])
continue
}
// 当出现大于栈顶元素时,循环比对进行弹栈
for len(nowStack) > 0 && height[i+j] >= nowStack[len(nowStack)-1] {
nowStack = nowStack[:len(nowStack)-1]
}
nowStack = append(nowStack, height[i+j])
}
stacks = append(stacks, nowStack)
res += len(nowStack)
}
return res
}
func main() {
fmt.Println(numberOfMountainSeen([]int{16,5,3,10,21,7}))
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。