-
Notifications
You must be signed in to change notification settings - Fork 0
/
295.go
116 lines (97 loc) · 2.27 KB
/
295.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package p295
/**
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
Examples:
[2,3,4] , the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
For example:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
*/
// a max heap and a min heap
type MaxPq struct {
pq []int
}
func (p *MaxPq) swim(k int) {
for k > 0 && p.pq[(k-1)>>1] < p.pq[k] {
p.pq[(k-1)>>1], p.pq[k] = p.pq[k], p.pq[(k-1)>>1]
k = (k - 1) >> 1
}
}
func (p *MaxPq) sink(k int) {
n := len(p.pq)
for (k<<1)+1 < n {
j := (k << 1) + 1
if j < n-1 && p.pq[j] < p.pq[j+1] {
j++
}
if p.pq[j] > p.pq[k] {
p.pq[j], p.pq[k] = p.pq[k], p.pq[j]
} else {
break
}
k = j
}
}
func (p *MaxPq) Insert(v int) {
n := len(p.pq)
p.pq = append(p.pq, v)
p.swim(n)
}
func (p *MaxPq) Max() int {
return p.pq[0]
}
func (p *MaxPq) DelMax() {
n := len(p.pq)
p.pq[0], p.pq[n-1] = p.pq[n-1], p.pq[0]
p.pq = p.pq[:n-1]
p.sink(0)
}
func (p *MaxPq) Empty() bool {
return len(p.pq) == 0
}
type MedianFinder struct {
maxHeap MaxPq
minHeap MaxPq
}
/** initialize your data structure here. */
func Constructor() MedianFinder {
return MedianFinder{
maxHeap: MaxPq{make([]int, 0)},
minHeap: MaxPq{make([]int, 0)},
}
}
func (this *MedianFinder) AddNum(num int) {
this.maxHeap.Insert(num)
max := this.maxHeap.Max()
this.minHeap.Insert(-max)
this.maxHeap.DelMax()
if len(this.maxHeap.pq) < len(this.minHeap.pq) {
min := -this.minHeap.Max()
this.maxHeap.Insert(min)
this.minHeap.DelMax()
}
}
func (this *MedianFinder) FindMedian() float64 {
res := 0.0
if len(this.maxHeap.pq) == len(this.minHeap.pq) {
res = float64(this.maxHeap.Max()-this.minHeap.Max()) / 2.0
} else if len(this.maxHeap.pq) < len(this.minHeap.pq) {
res = float64(-this.minHeap.Max())
} else {
res = float64(this.maxHeap.Max())
}
return res
}
/**
* Your MedianFinder object will be instantiated and called as such:
* obj := Constructor();
* obj.AddNum(num);
* param_2 := obj.FindMedian();
*/