239.滑动窗口最大值

leetcode

使用container.heap包实现大根堆。需要维护数据的index来判断是否在窗口内。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
var a []int
func maxSlidingWindow(nums []int, k int) []int {
a = nums
h := &Heap{}
heap.Init(h)
ans := []int{}

for i := 0; i < len(nums); i++ {
heap.Push(h, i)
for h.slice[0] <= i - k {
heap.Pop(h)
}
// fmt.Printf("h: %v\n", h)
if i >= k - 1 {
ans = append(ans, nums[h.slice[0]])
}
}
return ans
}

type Heap struct {
slice sort.IntSlice
}

func (h Heap) Len() int {
return len(h.slice)
}

func (h Heap) Swap(i, j int) {
h.slice[i], h.slice[j] = h.slice[j], h.slice[i]
}

func (h Heap) Less(i, j int) bool {
return a[h.slice[i]] > a[h.slice[j]]
}

func (h *Heap) Push(x interface{}) {
h.slice = append(h.slice, x.(int))
}

func (h *Heap) Pop() interface{} {
old := h.slice
n := len(old)
x := old[n-1]
h.slice = old[:n-1]
return x
}



type NodeHeap []Node

func (nh NodeHeap) Len() int {
return len(nh)
}

func (nh NodeHeap) Swap(i, j int) {
nh[i], nh[j] = nh[j], nh[i]
}
func (nh NodeHeap) Less(i, j int) bool {
if nh[i].count > nh[j].count {
return true
}

if nh[i].count == nh[j].count {
if nh[i].x + nh[i].y < nh[j].x + nh[j].y{
return true
}

if nh[i].x + nh[i].y == nh[j].x + nh[j].y && nh[i].x < nh[].x{
return true
}
}

return nh[i].Area() < nh[j].Area()
}

func (nh *NodeHeap) Push(h interface{}) {
*nh = append(*nh, h.(Node))
}
func (nh *NodeHeap) Pop() (x interface{}) {
n := len(*nh)
x = (*nh)[n-1]
*nh = (*nh)[:n-1]
return x
}

239.滑动窗口最大值
https://blog.jerrylee.me/2021/09/4dd2603238eb.html
作者
Jerry Lee
发布于
2021年9月20日
许可协议