forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0295-find-median-from-data-stream.go
50 lines (42 loc) · 1.28 KB
/
0295-find-median-from-data-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
typeIntHeap []int
func (hIntHeap) Len() int { returnlen(h) }
func (hIntHeap) Less(i, jint) bool { returnh[i] <h[j] }
func (hIntHeap) Swap(i, jint) { h[i], h[j] =h[j], h[i] }
func (h*IntHeap) Push(xinterface{}) {*h=append(*h, x.(int))}
func (h*IntHeap) Pop() interface{} {
old:=*h
n:=len(old)
x:=old[n-1]
*h=old[0 : n-1]
returnx
}
typeMedianFinderstruct {
smallIntHeap
largeIntHeap
}
funcConstructor() MedianFinder {
returnMedianFinder{small: IntHeap{}, large: IntHeap{}}
}
func (this*MedianFinder) AddNum(numint) {
iflen(this.large) >0&&num>this.large[0] {
heap.Push(&this.large, num)
} else {
heap.Push(&this.small, -1*num)
}
iflen(this.small) >len(this.large) +1 {
val:=-1*heap.Pop(&this.small).(int)
heap.Push(&this.large, val)
}
iflen(this.large) >len(this.small) +1 {
val:=heap.Pop(&this.large).(int)
heap.Push(&this.small, -1*val)
}
}
func (this*MedianFinder) FindMedian() float64 {
iflen(this.small) >len(this.large) {
returnfloat64(-1*this.small[0])
} elseiflen(this.large) >len(this.small) {
returnfloat64(this.large[0])
}
returnfloat64(-1*this.small[0] +this.large[0]) /2
}