-
Notifications
You must be signed in to change notification settings - Fork 0
/
295-find-median-from-data-stream.py
70 lines (50 loc) · 1.93 KB
/
295-find-median-from-data-stream.py
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
class MedianFinder:
def __init__(self):
self.top = []
self.bottom = []
def addNum(self, num: int) -> None:
self.pushheap(self.top, num)
self.pushheap(self.bottom, -self.popheap(self.top))
if len(self.top) < len(self.bottom):
self.pushheap(self.top, -self.popheap(self.bottom))
def findMedian(self) -> float:
n, m = len(self.top), len(self.bottom)
if n == m:
return (self.top[0] - self.bottom[0]) / 2
else:
return self.top[0]
def pushheap(self, heap, num) -> None:
heap.append(num)
i = len(heap) - 1
parent = (i-1) // 2
while parent >= 0 and heap[parent] > heap[i]:
heap[parent], heap[i] = heap[i], heap[parent]
i = parent
parent = (i-1) // 2
def popheap(self, heap) -> int:
if len(heap) <= 1:
return None if not heap else heap.pop(0)
out = heap[0]
heap[0] = heap.pop(-1)
parent = 0
lchild, rchild = 1, 2
n = len(heap)
while lchild < n:
# case: single child
if lchild == n-1:
if heap[parent] > heap[lchild]:
heap[parent], heap[lchild] = heap[lchild], heap[parent]
break
smallChild = lchild if heap[lchild] < heap[rchild] else rchild
# if parent <= smallest child, conditions for heap are met
if heap[parent] <= heap[smallChild]:
break
# otherwise swap with smallest child
heap[parent], heap[smallChild] = heap[smallChild], heap[parent]
parent = smallChild
lchild, rchild = 2*parent+1, 2*parent+2
return out
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()