-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy pathsliding_max.go
50 lines (41 loc) · 1021 Bytes
/
sliding_max.go
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
package heap
import "container/heap"
type slidingWindow []int
// MaxSlidingWindow solves the problem in O(n*Log k) time and O(k) space.
func MaxSlidingWindow(numbers []int, k int) []int {
output := []int{}
if len(numbers) <= 1 || len(numbers) < k {
return output
}
pq := make(slidingWindow, k)
i := 0
for i < k {
pq[i] = numbers[i]
i++
}
heap.Init(&pq)
output = append(output, pq[0])
for i < len(numbers) {
for j := range k {
if pq[j] == numbers[i-k] {
pq[j] = pq[len(pq)-1]
pq = pq[:len(pq)-1]
break
}
}
heap.Push(&pq, numbers[i])
output = append(output, pq[0])
i++
}
return output
}
func (m slidingWindow) Len() int { return len(m) }
func (m slidingWindow) Less(i, j int) bool { return m[i] > m[j] }
func (m slidingWindow) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func (m *slidingWindow) Push(x any) { *m = append(*m, x.(int)) }
func (m *slidingWindow) Pop() any {
old := *m
tmp := old[len(old)-1]
*m = old[0 : len(old)-1]
return tmp
}