1 Star 0 Fork 0

catyMap/AlgorithmNote

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
maxSlidingWindow.go 991 Bytes
一键复制 编辑 原始数据 按行查看 历史
dogemap 提交于 2022-01-22 21:52 +08:00 . 更新题库
package main
import "container/heap"
type pair struct {
value, idx int
}
type pairs []pair
func (p pairs) Len() int {
return len(p)
}
// 大根堆
func (p pairs) Less(i, j int) bool {
return p[i].value > p[j].value
}
func (p pairs) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func (p *pairs) Pop() interface{} {
n := p.Len()
t := (*p)[n-1]
*p = (*p)[:n-1]
return t
}
func (p *pairs) Push(x interface{}) {
(*p) = append((*p), x.(pair))
}
// [1, -1] 1
func maxSlidingWindow(nums []int, k int) []int {
n := len(nums)
res := []int{}
if k == 0 {
res := make([]int, n, n)
return res
}
// 初始化堆
pHeap := make(pairs, 0, 0)
heap.Init(&pHeap)
for i := 0; i < k; i++ {
heap.Push(&pHeap, pair{nums[i], i})
}
res = append(res, pHeap[0].value)
for i := 1; i+k-1 < n; i++ {
for pHeap.Len() > 0 && pHeap[0].idx < i {
heap.Pop(&pHeap)
}
heap.Push(&pHeap, pair{nums[i+k-1], i + k - 1})
res = append(res, pHeap[0].value)
}
return res
}
func main() {
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/dogemap/algorithm-note.git
git@gitee.com:dogemap/algorithm-note.git
dogemap
algorithm-note
AlgorithmNote
dc486f96f6c1

搜索帮助