-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkth-largest-element-in-a-stream.go
80 lines (70 loc) · 1.63 KB
/
kth-largest-element-in-a-stream.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
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
// You can edit this code!
// Click here and start typing.
package main
import "fmt"
func main() {
a := Constructor(3, []int{4, 5, 8, 2})
var r int
r = a.Add(3)
fmt.Println(r)
r = a.Add(5)
fmt.Println(r)
r = a.Add(10)
fmt.Println(r)
r = a.Add(9)
fmt.Println(r)
r = a.Add(4)
fmt.Println(r)
}
type KthLargest struct {
minheap []int
size int
}
func Constructor(k int, nums []int) KthLargest {
h := new(KthLargest)
h.size = k
for _, v := range nums {
h.Add(v)
}
return *h
}
func (this *KthLargest) Heapify(val int) {
smallest := val
l := 2*val + 1
r := 2*val + 2
n := len(this.minheap)
if l < n && this.minheap[l] < this.minheap[smallest] {
smallest = l
}
if r < n && this.minheap[r] < this.minheap[smallest] {
smallest = r
}
if val != smallest {
this.minheap[smallest], this.minheap[val] = this.minheap[val], this.minheap[smallest]
this.Heapify(smallest)
}
}
func (this *KthLargest) ExtractRoot() {
this.minheap[0], this.minheap[len(this.minheap)-1] = this.minheap[len(this.minheap)-1], this.minheap[0]
this.minheap = this.minheap[:len(this.minheap)-1]
this.Heapify(0)
}
func (this *KthLargest) Add(val int) int {
if len(this.minheap) == 0 {
this.minheap = append(this.minheap, val)
return this.minheap[0]
}
if len(this.minheap) == this.size && val < this.minheap[0] {
return this.minheap[0]
}
if len(this.minheap) == this.size {
this.ExtractRoot()
}
this.minheap = append(this.minheap, val)
i := len(this.minheap) - 1
for i > 0 && this.minheap[i] <= this.minheap[(i-1)/2] {
this.minheap[(i-1)/2], this.minheap[i] = this.minheap[i], this.minheap[(i-1)/2]
i = (i - 1) / 2
}
return this.minheap[0]
}