1 Star 0 Fork 0

catyMap/AlgorithmNote

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
numberOfMountainSeen.go 1.49 KB
一键复制 编辑 原始数据 按行查看 历史
catyMap 提交于 2021-05-15 22:06 +08:00 . 添加一些栈题目
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}))
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/dogemap/algorithm-note.git
git@gitee.com:dogemap/algorithm-note.git
dogemap
algorithm-note
AlgorithmNote
dc486f96f6c1

搜索帮助